Python 中 if 语句中 &&(逻辑与)的等价词是什么?
- 2025-02-08 08:52:00
- admin 原创
- 54
问题描述:
这不起作用:
if cond1 && cond2:
解决方案 1:
使用and
而不是&&
。
解决方案 2:
Python 用途and
和or
条件。
IE
if foo == 'abc' and bar == 'bac' or zoo == '123':
# do something
解决方案 3:
我在 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):
一些额外的信息(可能会有用):
我在这个表中总结了运算符“等价”:
操作员(其他语言) | 运算符 (Python) | ||
---|---|---|---|
&& | and | ||
` | ` | or | |
! | not |
另请参阅Python 文档:6.11。布尔运算。
除了逻辑运算符之外,Python 还有按位/二进制运算符:
逻辑运算符 | 按位运算符 | |
---|---|---|
and | & | |
or | ` | ` |
Python 中没有按位否定(只有按位逆运算符~
- 但这并不等同于not
)。
另请参阅6.6. 一元算术和按位/二进制运算和6.7. 二进制算术运算。
逻辑运算符(与许多其他语言一样)具有短路的优点。这意味着如果第一个操作数已经定义了结果,则根本不会评估第二个运算符。
为了说明这一点,我使用了一个函数,它只接受一个值,打印并再次返回。这很方便查看实际求值的内容,因为有打印语句:
>>> 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
为了总结这一点,这里有另一个表格:
表达 | 右侧评估? |
---|---|
True 和 ... | 是的 |
False 和 ... | 不 |
True 或者 ... | 不 |
False 或者 ... | 是的 |
和代表返回什么,它们不必是或,它们只需要在调用它们时返回或True
( 1)。False
`bool(left-hand-side)True
FalseTrue
False`bool
因此,在伪代码(!)中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
因为它们是关键字。此外,您永远不应使用“evaluate”或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
结果。因此这些细节可能与你无关。
解决方案 4:
两条评论:
在 Python 中使用
and
andor
进行逻辑运算。使用 4 个空格缩进,而不是 2 个。稍后您会感谢自己,因为您的代码看起来与其他人的代码几乎相同。有关更多详细信息,请参阅PEP 8 。
解决方案 5:
我采用了纯数学的解决方案:
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:]
解决方案 6:
您可以使用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
希望这有帮助!
解决方案 7:
这可能不是这个任务的最佳代码,但正在发挥作用 -
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:]
解决方案 8:
在条件中使用“and”。我在 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
解决方案 9:
单个&
(不是双&&
)就足够了,或者如上面的答案所示,你可以使用“and”。我在熊猫中也发现了这一点
cities['Is wide and has saint name'] = (cities['Population'] > 1000000)
& cities['City name'].apply(lambda name: name.startswith('San'))
如果我们用“and”代替“&”,它就不会起作用。