Python 相当于 if 语句中的 &&(逻辑与)
-
21-09-2019 - |
题
这是我的代码:
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 条件中遇到错误。我究竟做错了什么?
解决方案
您想and
代替&&
。
其他提示
Python使用and
和or
条件句。
即
if foo == 'abc' and bar == 'bac' or zoo == '123':
# do something
两个意见:
- 使用
and
和or
为逻辑操作中蟒蛇。 - 使用4个空间缩进,而不是2.你会感谢你自己以后因为你的代码看起来漂亮多其他人一样的代码。看看 PEP8 更多的细节。
我在 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 文档:6.11.布尔运算.
除了逻辑运算符之外,Python 还具有按位/二元运算符:
+--------------------+--------------------+
| Logical operator | Bitwise operator |
+====================+====================+
| 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
为了总结这一点,这里有另一个表:
+-----------------+-------------------------+
| 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)。
所以在伪代码(!)中 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
call 可用于自定义类的行为方式 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
关于结果。因此,这些细节可能与您无关。
我用purlely数学解去:
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:]
在一个 “如果声明” 在Python,你会使用和,或不,然后这些等同于 &&,||!的逻辑,其主要应用在运营商其它的编程语言
的使用“和”在条件。我在Jupyter笔记本导入时经常使用这样的:
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
一个单&
(未双&&
)足够或作为顶部答案提示可以使用“和”。
我还发现这在大熊猫
cities['Is wide and has saint name'] = (cities['Population'] > 1000000)
& cities['City name'].apply(lambda name: name.startswith('San'))
如果我们更换“和”与“和”,它不会工作。
可能与&代替%是更快速和十个分量可读性
其它测试偶/奇
x是偶数? X%2 == 0
x是奇数?不X%2 == 0
也许是与按位和1
更清晰x是奇数? 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