使用 and
而不是 &&
。
Python 使用 and
和 or
条件。
IE
if foo == 'abc' and bar == 'bac' or zoo == '123':
# do something
我在 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):
一些附加信息(可能会派上用场):
我在此表中总结了运算符“等价物”:
+------------------------------+---------------------+
| Operator (other languages) | Operator (Python) |
+==============================+=====================+
| && | and |
+------------------------------+---------------------+
| || | or |
+------------------------------+---------------------+
| ! | not |
+------------------------------+---------------------+
另见Python documentation: 6.11. Boolean operations。
除了逻辑运算符 Python 还具有位/二元运算符:
+--------------------+--------------------+
| Logical operator | Bitwise operator |
+====================+====================+
| and | & |
+--------------------+--------------------+
| or | | |
+--------------------+--------------------+
Python 中没有按位否定(只有按位逆运算符 ~
- 但它不 等同于 not
)。
另请参阅 6.6. Unary arithmetic and bitwise/binary operations 和 6.7. Binary arithmetic operations。
逻辑运算符(与许多其他语言一样)具有短路的优点。这意味着如果第一个操作数已经定义了结果,则根本不计算第二个运算符。
为了证明这一点,我使用了一个函数,它只接受一个值,打印它并再次返回它。由于打印语句,这很方便查看实际评估的内容:
>>> def print_and_return(value):
... print(value)
... return value
>>> res = print_and_return(False) and print_and_return(True)
False
正如您所看到的,只执行了一条打印语句,因此 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
,它们只需要在调用 bool
时返回 True
或 False
(1)。
因此,在 Pseudo-Code(!) 中,and
和 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__
方法以及它是否返回大于零的值。如果您创建一个序列容器,这可能很有用。
NumPy 数组和子类
可能有点超出原始问题的范围,但如果您正在处理 NumPy 数组或子类(如 Pandas 系列或 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)
这是因为如果第一个操作数的计算结果为 False
,则 and
实际上返回第一个操作数,如果计算结果为 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
。因此,这些细节可能与您无关。
两条评论:
在 Python 中使用 and 和 or 进行逻辑运算。
使用 4 个空格而不是 2 个空格进行缩进。稍后您会感谢自己,因为您的代码看起来与其他所有人的代码几乎相同。有关详细信息,请参阅 PEP 8。
我选择了一个纯粹的数学解决方案:
def front_back(a, b):
return a[:(len(a)+1)//2]+b[:(len(b)+1)//2]+a[(len(a)+1)//2:]+b[(len(b)+1)//2:]
您可以使用 and
和 or
来执行 C、C++ 中的逻辑运算。就像字面上的 and
是 &&
而 or
是 ||
。
看看这个有趣的例子,
假设你想用 Python 构建逻辑门:
def AND(a,b):
return (a and b) #using and operator
def OR(a,b):
return (a or b) #using or operator
现在尝试打电话给他们:
print AND(False, False)
print OR(True, False)
这将输出:
False
True
希望这可以帮助!
可能这不是此任务的最佳代码,但正在工作 -
def front_back(a, b):
if len(a) % 2 == 0 and len(b) % 2 == 0:
print a[:(len(a)/2)] + b[:(len(b)/2)] + a[(len(a)/2):] + b[(len(b)/2):]
elif len(a) % 2 == 1 and len(b) % 2 == 0:
print a[:(len(a)/2)+1] + b[:(len(b)/2)] + a[(len(a)/2)+1:] + b[(len(b)/2):]
elif len(a) % 2 == 0 and len(b) % 2 == 1:
print a[:(len(a)/2)] + b[:(len(b)/2)+1] + a[(len(a)/2):] + b[(len(b)/2)+1:]
else :
print a[:(len(a)/2)+1] + b[:(len(b)/2)+1] + a[(len(a)/2)+1:] + b[(len(b)/2)+1:]
在条件句中使用“和”。我在 Jupyter Notebook 中导入时经常使用这个:
def find_local_py_scripts():
import os # does not cost if already imported
for entry in os.scandir('.'):
# find files ending with .py
if entry.is_file() and entry.name.endswith(".py") :
print("- ", entry.name)
find_local_py_scripts()
- googlenet_custom_layers.py
- GoogLeNet_Inception_v1.py
也许用 & 代替 % 更快并且保持可读性
其他测试偶数/奇数
是偶数? x % 2 == 0
x 是奇数吗?不是 x % 2 == 0
按位和 1 可能更清楚
是奇数吗? x & 1
x 是偶数?不是 x & 1(不是奇数)
def front_back(a, b):
# +++your code here+++
if not len(a) & 1 and not len(b) & 1:
return a[:(len(a)/2)] + b[:(len(b)/2)] + a[(len(a)/2):] + b[(len(b)/2):]
else:
#todo! Not yet done. :P
return
单个 &
(而不是双 &&
)就足够了,或者如最佳答案所示,您可以使用“和”。我也在熊猫中发现了这个
cities['Is wide and has saint name'] = (cities['Population'] > 1000000)
& cities['City name'].apply(lambda name: name.startswith('San'))
如果我们将“&”替换为“and”,它将不起作用。
&&
和AND
后到达这里并得到一个错误(不希望 python 想要小写单词and
)。