亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Python在if語句中等同于&&(logical-and)

Python在if語句中等同于&&(logical-and)

千萬里不及你 2019-09-19 08:40:39
這是我的代碼:def front_back(a, b):   # +++your code here+++   if len(a) % 2 == 0 && len(b) % 2 == 0:     return a[:(len(a)/2)] + b[:(len(b)/2)] + a[(len(a)/2):] + b[(len(b)/2):]    else:     #todo! Not yet done. :P   return我在IF條件中遇到錯誤。我究竟做錯了什么?
查看完整描述

4 回答

?
慕俠2389804

TA貢獻1719條經驗 獲得超6個贊

你會想要and而不是&&


查看完整回答
反對 回復 2019-09-19
?
慕村225694

TA貢獻1880條經驗 獲得超4個贊

兩條評論:

  • 在Python中使用andor進行邏輯運算。

  • 使用4個空格來縮進而不是2.稍后你會感謝自己,因為你的代碼與其他人的代碼看起來非常相似。有關詳細信息,請參閱PEP 8


查看完整回答
反對 回復 2019-09-19
?
莫回無

TA貢獻1865條經驗 獲得超7個贊

我在IF條件中遇到錯誤。我究竟做錯了什么?


你得到的原因SyntaxError是&&Python中沒有運算符。同樣||和!是不是有效的Python運營商。


您可能從其他語言中了解到的某些運算符在Python中具有不同的名稱。邏輯運算符&&和||實際上叫and和or。同樣,!調用邏輯否定運算符not。


所以你可以寫:


if len(a) % 2 == 0 and len(b) % 2 == 0:

甚至:


if not (len(a) % 2 or len(b) % 2):

一些額外的信息(可能派上用場):

我在此表中總結了運算符“equivalent”:


+------------------------------+---------------------+

|  Operator (other languages)  |  Operator (Python)  |

+==============================+=====================+

|              &&              |         and         |

+------------------------------+---------------------+

|              ||              |         or          |

+------------------------------+---------------------+

|              !               |         not         |

+------------------------------+---------------------+

另見Python文檔:6.11。布爾運算。


除了邏輯運算符,Python還有按位/二元運算符:


+--------------------+--------------------+

|  Logical operator  |  Bitwise operator  |

+====================+====================+

|        and         |         &          |

+--------------------+--------------------+

|         or         |         |          |

+--------------------+--------------------+

Python中沒有按位否定(只是按位逆運算符~- 但這不等同于not)。


另見6.6。一元算術和按位/二進制運算和6.7。二進制算術運算。


邏輯運算符(與許多其他語言一樣)具有這些短路的優點。這意味著如果第一個操作數已經定義了結果,則根本不評估第二個操作符。


為了表明這一點,我使用一個只需要一個值的函數,打印它并再次返回它。由于print語句,這對于查看實際評估的內容非常方便:


>>> def print_and_return(value):

...     print(value)

...     return value


>>> res = print_and_return(False) and print_and_return(True)

False

正如您所看到的,只執行了一個print語句,因此Python甚至沒有查看正確的操作數。


二元運算符不是這種情況。那些總是評估兩個操作數:


>>> res = print_and_return(False) & print_and_return(True);

False

True

但是,如果第一個操作數不夠,那么當然會評估第二個操作符:


>>> res = print_and_return(True) and print_and_return(False);

True

False

總結這里是另一個表:


+-----------------+-------------------------+

|   Expression    |  Right side evaluated?  |

+=================+=========================+

| `True` and ...  |           Yes           |

+-----------------+-------------------------+

| `False` and ... |           No            |

+-----------------+-------------------------+

|  `True` or ...  |           No            |

+-----------------+-------------------------+

| `False` or ...  |           Yes           |

+-----------------+-------------------------+

在True與False代表什么bool(left-hand-side)返回,他們不必是True或False,他們只需要返回True或False當bool被要求他們(1)。


所以在Pseudo-Code(?。┲衋nd,or函數的工作原理如下:


def and(expr1, expr2):

    left = evaluate(expr1)

    if bool(left):

        return evaluate(expr2)

    else:

        return left


def or(expr1, expr2):

    left = evaluate(expr1)

    if bool(left):

        return left

    else:

        return evaluate(expr2)

請注意,這是偽代碼而不是Python代碼。在Python中,您無法創建被調用的函數,and或者or因為它們是關鍵字。你也不應該使用“評估”或if bool(...)。


自定義您自己的類的行為

此隱式bool調用可用于自定義類的行為方式and,or以及not。


為了展示如何定制這個,我使用這個類print來跟蹤發生的事情:


class Test(object):

    def __init__(self, value):

        self.value = value


    def __bool__(self):

        print('__bool__ called on {!r}'.format(self))

        return bool(self.value)


    __nonzero__ = __bool__  # Python 2 compatibility


    def __repr__(self):

        return "{self.__class__.__name__}({self.value})".format(self=self)

那么讓我們看看該類與這些運算符結合發生了什么:


>>> if Test(True) and Test(False):

...     pass

__bool__ called on Test(True)

__bool__ called on Test(False)


>>> if Test(False) or Test(False):

...     pass

__bool__ called on Test(False)

__bool__ called on Test(False)


>>> if not Test(True):

...     pass

__bool__ called on Test(True)

如果您沒有__bool__方法,那么Python還會檢查對象是否有__len__方法,以及它是否返回大于零的值。如果您創建序列容器,這可能是有用的。


另見4.1。真值測試。


NumPy數組和子類

可能有點超出原始問題的范圍但是如果你正在處理NumPy數組或子類(如Pandas Series或DataFrames),那么隱式bool調用將引發可怕的ValueError:


>>> import numpy as np

>>> arr = np.array([1,2,3])

>>> bool(arr)

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

>>> arr and arr

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()


>>> import pandas as pd

>>> s = pd.Series([1,2,3])

>>> bool(s)

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

>>> s and s

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

在這些情況下,您可以使用NumPy中的邏輯和函數,它執行元素and(或or):


>>> np.logical_and(np.array([False,False,True,True]), np.array([True, False, True, False]))

array([False, False,  True, False])

>>> np.logical_or(np.array([False,False,True,True]), np.array([True, False, True, False]))

array([ True, False,  True,  True])

如果你只處理布爾數組,你也可以使用NumPy的二元運算符,這些運算符執行元素(也是二進制)比較:


>>> np.array([False,False,True,True]) & np.array([True, False, True, False])

array([False, False,  True, False])

>>> np.array([False,False,True,True]) | np.array([True, False, True, False])

array([ True, False,  True,  True])

(1)


bool對操作數的調用必須返回True或False不完全正確。它只是需要在其__bool__方法中返回布爾值的第一個操作數:


class Test(object):

    def __init__(self, value):

        self.value = value


    def __bool__(self):

        return self.value


    __nonzero__ = __bool__  # Python 2 compatibility


    def __repr__(self):

        return "{self.__class__.__name__}({self.value})".format(self=self)


>>> x = Test(10) and Test(10)

TypeError: __bool__ should return bool, returned int

>>> x1 = Test(True) and Test(10)

>>> x2 = Test(False) and Test(10)

那是因為and如果第一個操作數的計算結果實際返回第一個操作數,False并且如果它的計算結果為,True則返回第二個操作數:


>>> x1

Test(10)

>>> x2

Test(False)

同樣的,or但反過來說:


>>> Test(True) or Test(10)

Test(True)

>>> Test(False) or Test(10)

Test(10)

但是,如果您在if語句中使用它們,if則還會隱式調用bool結果。所以這些細節可能與您無關。


查看完整回答
反對 回復 2019-09-19
  • 4 回答
  • 0 關注
  • 6445 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號