4 回答

TA貢獻(xiàn)1865條經(jīng)驗(yàn) 獲得超7個(gè)贊
我在IF條件中遇到錯(cuò)誤。我究竟做錯(cuò)了什么?
你得到的原因SyntaxError是&&Python中沒有運(yùn)算符。同樣||和!是不是有效的Python運(yùn)營(yíng)商。
您可能從其他語言中了解到的某些運(yùn)算符在Python中具有不同的名稱。邏輯運(yùn)算符&&和||實(shí)際上叫and和or。同樣,!調(diào)用邏輯否定運(yùn)算符not。
所以你可以寫:
if len(a) % 2 == 0 and len(b) % 2 == 0:
甚至:
if not (len(a) % 2 or len(b) % 2):
一些額外的信息(可能派上用場(chǎng)):
我在此表中總結(jié)了運(yùn)算符“equivalent”:
+------------------------------+---------------------+
| Operator (other languages) | Operator (Python) |
+==============================+=====================+
| && | and |
+------------------------------+---------------------+
| || | or |
+------------------------------+---------------------+
| ! | not |
+------------------------------+---------------------+
另見Python文檔:6.11。布爾運(yùn)算。
除了邏輯運(yùn)算符,Python還有按位/二元運(yùn)算符:
+--------------------+--------------------+
| Logical operator | Bitwise operator |
+====================+====================+
| and | & |
+--------------------+--------------------+
| or | | |
+--------------------+--------------------+
Python中沒有按位否定(只是按位逆運(yùn)算符~- 但這不等同于not)。
另見6.6。一元算術(shù)和按位/二進(jìn)制運(yùn)算和6.7。二進(jìn)制算術(shù)運(yùn)算。
邏輯運(yùn)算符(與許多其他語言一樣)具有這些短路的優(yōu)點(diǎn)。這意味著如果第一個(gè)操作數(shù)已經(jīng)定義了結(jié)果,則根本不評(píng)估第二個(gè)操作符。
為了表明這一點(diǎn),我使用一個(gè)只需要一個(gè)值的函數(shù),打印它并再次返回它。由于print語句,這對(duì)于查看實(shí)際評(píng)估的內(nèi)容非常方便:
>>> def print_and_return(value):
... print(value)
... return value
>>> res = print_and_return(False) and print_and_return(True)
False
正如您所看到的,只執(zhí)行了一個(gè)print語句,因此Python甚至沒有查看正確的操作數(shù)。
二元運(yùn)算符不是這種情況。那些總是評(píng)估兩個(gè)操作數(shù):
>>> res = print_and_return(False) & print_and_return(True);
False
True
但是,如果第一個(gè)操作數(shù)不夠,那么當(dāng)然會(huì)評(píng)估第二個(gè)操作符:
>>> res = print_and_return(True) and print_and_return(False);
True
False
總結(jié)這里是另一個(gè)表:
+-----------------+-------------------------+
| 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當(dāng)bool被要求他們(1)。
所以在Pseudo-Code(!)中and,or函數(shù)的工作原理如下:
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)
請(qǐng)注意,這是偽代碼而不是Python代碼。在Python中,您無法創(chuàng)建被調(diào)用的函數(shù),and或者or因?yàn)樗鼈兪顷P(guān)鍵字。你也不應(yīng)該使用“評(píng)估”或if bool(...)。
自定義您自己的類的行為
此隱式bool調(diào)用可用于自定義類的行為方式and,or以及not。
為了展示如何定制這個(gè),我使用這個(gè)類print來跟蹤發(fā)生的事情:
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)
那么讓我們看看該類與這些運(yùn)算符結(jié)合發(fā)生了什么:
>>> 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還會(huì)檢查對(duì)象是否有__len__方法,以及它是否返回大于零的值。如果您創(chuàng)建序列容器,這可能是有用的。
另見4.1。真值測(cè)試。
NumPy數(shù)組和子類
可能有點(diǎn)超出原始問題的范圍但是如果你正在處理NumPy數(shù)組或子類(如Pandas Series或DataFrames),那么隱式bool調(diào)用將引發(fā)可怕的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中的邏輯和函數(shù),它執(zhí)行元素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])
如果你只處理布爾數(shù)組,你也可以使用NumPy的二元運(yùn)算符,這些運(yùn)算符執(zhí)行元素(也是二進(jìn)制)比較:
>>> 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對(duì)操作數(shù)的調(diào)用必須返回True或False不完全正確。它只是需要在其__bool__方法中返回布爾值的第一個(gè)操作數(shù):
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)
那是因?yàn)閍nd如果第一個(gè)操作數(shù)的計(jì)算結(jié)果實(shí)際返回第一個(gè)操作數(shù),F(xiàn)alse并且如果它的計(jì)算結(jié)果為,True則返回第二個(gè)操作數(shù):
>>> x1
Test(10)
>>> x2
Test(False)
同樣的,or但反過來說:
>>> Test(True) or Test(10)
Test(True)
>>> Test(False) or Test(10)
Test(10)
但是,如果您在if語句中使用它們,if則還會(huì)隱式調(diào)用bool結(jié)果。所以這些細(xì)節(jié)可能與您無關(guān)。
添加回答
舉報(bào)