Python在if语句中等同于&&(logical-and)

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而不是&&.

  • @diffracteD:如果要覆盖标准运算符优先级,请使用括号(您可以在此处了解:http://www.ibiblio.org/g2swap/byteofpython/read/operator-precedence.html) (7认同)
  • 我在同时输入`&&`和`AND`之后到达了这里,但出现了一个错误(不希望python想要小写的单词`and`)。 (6认同)
  • 我应该为此做些什么:如果x =='n'和y =='a'或y =='b':<要做某事>它会起作用!@ChristopheD (2认同)
  • 我喜欢[David Titarenco](http://stackoverflow.com/users/243613/david-titarenco)进行了剪切粘贴[示例](http://stackoverflow.com/a/2485473/1153645) (2认同)
  • 我认为你应该使用 & 见:/sf/ask/2584536601/任何-o (2认同)

Dav*_*nco 216

Python使用andor条件.

if foo == 'abc' and bar == 'bac' or zoo == '123':
  # do something
Run Code Online (Sandbox Code Playgroud)

  • @Jeff你的第一条路.`和`[有更高的优先权](https://docs.python.org/2/reference/expressions.html#operator-precedence)比`或`. (10认同)
  • 你的例子是评估为"(如果这个和这个)或那个"或"如果这个和(这个或那个)"? (8认同)
  • 不要忘记python也没有(嗯,和!) (5认同)
  • @Matt表从最低优先级到最高优先级.如果你研究过布尔代数,那么记住优先级会更容易; "或"是加法,"和"是加法. (4认同)

ist*_*ble 37

两条评论:

  • 在Python中使用andor进行逻辑运算.
  • 使用4个空格来缩进而不是2.稍后你会感谢自己,因为你的代码与其他人的代码看起来非常相似.有关详细信息,请参阅PEP 8.


MSe*_*ert 33

我在IF条件中遇到错误.我究竟做错了什么?

你得到的原因SyntaxError&&Python中没有运算符.同样||!不是有效的Python运营商.

您可能从其他语言中了解到的某些运算符在Python中具有不同的名称.逻辑运算符&&||实际上叫andor.同样,!调用逻辑否定运算符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文档:6.11.布尔运算.

除了逻辑运算符,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)

TrueFalse代表什么bool(left-hand-side)返回,他们不必是TrueFalse,他们只需要返回TrueFalsebool被要求他们(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数组和子类

可能有点超出了原始问题的范围,但是如果您正在处理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对操作数的调用必须返回TrueFalse不完全正确.它只是需要在其__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)

  • 这不是实际问题的答案. (7认同)

gee*_*rsh 9

您可以使用andor执行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)