Python';s相当于&&;(逻辑and)在if语句中
这是我的密码:Python';s相当于&&;(逻辑and)在if语句中,python,if-statement,keyword,logical-operators,and-operator,Python,If Statement,Keyword,Logical Operators,And Operator,这是我的密码: 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条件中得到一个错误。 我做错了什么?
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条件中得到一个错误。我做错了什么?您希望使用
和而不是&
Python使用和和或条件
i、 e
两点意见:
- 在Python中使用
和
和或
进行逻辑操作
- 使用4个空格缩进,而不是2个空格。稍后您将感谢自己,因为您的代码看起来与其他人的代码几乎相同。有关更多详细信息,请参阅
这可能不是执行此任务的最佳代码,但正在运行-
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:]
我提出了一个明确的数学解决方案:
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:]
也许使用%(而不是%)会更快,并保持可读性
其他测试为偶数/奇数
x是偶数?x%2==0
x是奇数?不是x%2==0
按位和1可能更清楚
x是奇数?x&1
x是偶数?非x&1(非奇数)
使用<强> <代码>和<代码> >代码>或<强>,以执行C、C++中的逻辑操作。就像字面上的和是&
和或是|
看看这个有趣的例子,
假设您想用Python构建逻辑门:
现在试着给他们打电话:
print AND(False, False)
print OR(True, False)
这将输出:
希望这有帮助 在条件句中使用“and”。我在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
一个&
(而不是两个&&
)就足够了,或者正如上面的答案所示,您可以使用“and”。
我在熊猫身上也发现了这个
cities['Is wide and has saint name'] = (cities['Population'] > 1000000)
& cities['City name'].apply(lambda name: name.startswith('San'))
如果我们将“&”替换为“and”,它将不起作用
我在IF条件中得到一个错误。我做错了什么
得到一个SyntaxError
的原因是Python中没有&&
运算符。同样地,|
和代码>是无效的Python运算符
您可能从其他语言知道的一些运算符在Python中有不同的名称。
逻辑运算符&&
和|
实际上被称为和和或。
同样,逻辑求反运算符代码>被称为而不是
所以你可以写:
if len(a) % 2 == 0 and len(b) % 2 == 0:
甚至:
if not (len(a) % 2 or len(b) % 2):
一些附加信息(可能会派上用场):
我在此表中总结了运算符“等效项”:
+------------------------------+---------------------+
|运算符(其他语言)|运算符(Python)|
+==============================+=====================+
|&&&|和|
+------------------------------+---------------------+
|| | |或|
+------------------------------+---------------------+
| ! | 不是|
+------------------------------+---------------------+
另见
除了逻辑运算符之外,Python还具有位/二进制运算符:
>>> 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)
+--------------------+--------------------+
|逻辑运算符|位运算符|
+====================+====================+
|和|&|
+--------------------+--------------------+
|或| ||
+--------------------+--------------------+
Python中没有按位求反(只有按位求逆运算符~
——但它与不等价)
另见和
逻辑运算符(与许多其他语言一样)的优点是它们是短路的。
这意味着,如果第一个操作数已经定义了结果,那么第二个运算符就根本不计算
为了说明这一点,我使用了一个函数,它只需要获取一个值,打印它,然后再次返回它。这很方便,可以查看实际情况
由于打印语句而进行评估:
>>> 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
下面是另一个表,总结一下:
+-----------------+-------------------------+
|表达式|右侧已计算|
+=================+=========================+
|‘真’和……|对|
+-----------------+-------------------------+
|‘假’和……|没有|
+-----------------+-------------------------+
|‘真’还是……|没有|
+-----------------+-------------------------+
|‘假’或……|对|
+-----------------+-------------------------+
True
和False
表示bool(左侧)
返回的内容,它们不必是True
或False
,只要在调用bool
时返回True
或False即可(1)
因此,在伪代码(!)中,和
和或
函数的工作方式如下:
def和(expr1、expr2):
左=评估(expr1)
如果布尔(左):
返回评估(expr2)
其他:
左转
def或(expr1、expr2):
左=评估(expr1)
如果布尔(左):
左转
其他:
返回评估(expr2)
请注意,这是伪代码,而不是Python代码。在Python中,不能创建名为和
或或
的函数,因为它们是关键字。
此外,如果bool(…)
,则不应使用“evaluate”或
自定义自己类的行为
此隐式bool
调用可用于自定义类在和、或和非
情况下的行为
为了展示如何定制,我使用了这个类,它再次print
>>> def print_and_return(value):
... print(value)
... return value
>>> res = print_and_return(False) and print_and_return(True)
False
>>> res = print_and_return(False) & print_and_return(True);
False
True
>>> res = print_and_return(True) and print_and_return(False);
True
False
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)
>>> 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().
>>> 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])
>>> 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])
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)
>>> x1
Test(10)
>>> x2
Test(False)
>>> Test(True) or Test(10)
Test(True)
>>> Test(False) or Test(10)
Test(10)