769 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
Run Code Online (Sandbox Code Playgroud)
我在IF条件中遇到错误.我究竟做错了什么?
Chr*_*heD 1360
你会想要and而不是&&.
Dav*_*nco 216
Python使用and和or条件.
即
if foo == 'abc' and bar == 'bac' or zoo == '123':
# do something
Run Code Online (Sandbox Code Playgroud)
MSe*_*ert 33
我在IF条件中遇到错误.我究竟做错了什么?
你得到的原因SyntaxError是&&Python中没有运算符.同样||和!是不是有效的Python运营商.
您可能从其他语言中了解到的某些运算符在Python中具有不同的名称.逻辑运算符&&和||实际上叫and和or.同样,!调用逻辑否定运算符not.
所以你可以写:
if len(a) % 2 == 0 and len(b) % 2 == 0:
Run Code Online (Sandbox Code Playgroud)
甚至:
if not (len(a) % 2 or len(b) % 2):
Run Code Online (Sandbox Code Playgroud)
我在此表中总结了运算符"equivalent":
+------------------------------+---------------------+
| Operator (other languages) | Operator (Python) |
+==============================+=====================+
| && | and |
+------------------------------+---------------------+
| || | or |
+------------------------------+---------------------+
| ! | not |
+------------------------------+---------------------+
Run Code Online (Sandbox Code Playgroud)
除了逻辑运算符,Python还有按位/二元运算符:
+--------------------+--------------------+
| Logical operator | Bitwise operator |
+====================+====================+
| and | & |
+--------------------+--------------------+
| or | | |
+--------------------+--------------------+
Run Code Online (Sandbox Code Playgroud)
Python中没有按位否定(只是按位逆运算符~- 但这不等同于not).
另见6.6.一元算术和按位/二进制运算和6.7.二进制算术运算.
逻辑运算符(与许多其他语言一样)具有这些短路的优点.这意味着如果第一个操作数已经定义了结果,则根本不评估第二个操作符.
为了表明这一点,我使用一个只需要一个值的函数,打印它并再次返回它.由于print语句,这对于查看实际评估的内容非常方便:
>>> def print_and_return(value):
... print(value)
... return value
>>> res = print_and_return(False) and print_and_return(True)
False
Run Code Online (Sandbox Code Playgroud)
正如您所看到的,只执行了一个print语句,因此Python甚至没有查看正确的操作数.
二元运算符不是这种情况.那些总是评估两个操作数:
>>> res = print_and_return(False) & print_and_return(True);
False
True
Run Code Online (Sandbox Code Playgroud)
但是,如果第一个操作数不够,那么第二个操作符当然会被评估:
>>> res = print_and_return(True) and print_and_return(False);
True
False
Run Code Online (Sandbox Code Playgroud)
总结这里是另一个表:
+-----------------+-------------------------+
| Expression | Right side evaluated? |
+=================+=========================+
| `True` and ... | Yes |
+-----------------+-------------------------+
| `False` and ... | No |
+-----------------+-------------------------+
| `True` or ... | No |
+-----------------+-------------------------+
| `False` or ... | Yes |
+-----------------+-------------------------+
Run Code Online (Sandbox Code Playgroud)
在True与False代表什么bool(left-hand-side)返回,他们不必是True或False,他们只需要返回True或False当bool被要求他们(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)
Run Code Online (Sandbox Code Playgroud)
请注意,这是伪代码而不是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)
Run Code Online (Sandbox Code Playgroud)
那么让我们看看该类与这些运算符结合发生了什么:
>>> 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)
Run Code Online (Sandbox Code Playgroud)
如果您没有__bool__方法,那么Python还会检查对象是否有__len__方法,以及它是否返回大于零的值.如果您创建序列容器,这可能是有用的.
另见4.1.真值测试.
可能有点超出了原始问题的范围,但是如果您正在处理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().
Run Code Online (Sandbox Code Playgroud)
在这些情况下,您可以使用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])
Run Code Online (Sandbox Code Playgroud)
如果您只处理布尔数组,您也可以将二元运算符与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])
Run Code Online (Sandbox Code Playgroud)
(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)
Run Code Online (Sandbox Code Playgroud)
那是因为and如果第一个操作数的计算结果实际返回第一个操作数,False并且如果它的计算结果为,True则返回第二个操作数:
>>> x1
Test(10)
>>> x2
Test(False)
Run Code Online (Sandbox Code Playgroud)
同样的,or但反过来说:
>>> Test(True) or Test(10)
Test(True)
>>> Test(False) or Test(10)
Test(10)
Run Code Online (Sandbox Code Playgroud)
但是,如果您在if语句中使用它们,if则还会隐式调用bool结果.所以这些细节可能与您无关.
Big*_*Red 10
我选择了一个简单的数学解决方案:
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:]
Run Code Online (Sandbox Code Playgroud)
您可以使用and和or执行C,C++中的逻辑操作.就像字面上and是&&和or是||.
假设您想在Python中构建Logic Gates:
def AND(a,b):
return (a and b) #using and operator
def OR(a,b):
return (a or b) #using or operator
Run Code Online (Sandbox Code Playgroud)
现在尝试调用它们:
print AND(False, False)
print OR(True, False)
Run Code Online (Sandbox Code Playgroud)
False
True
Run Code Online (Sandbox Code Playgroud)
希望这可以帮助!
小智 5
可能这不是这项任务的最佳代码,但是有效 -
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:]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1859206 次 |
| 最近记录: |