标签归档:logical-operators

“和”和“或”如何与非布尔值一起使用?

问题:“和”和“或”如何与非布尔值一起使用?

我正在尝试学习python,并遇到了一些不错的代码,虽然简短但并不完全有意义

上下文是:

def fn(*args):
    return len(args) and max(args)-min(args)

我知道它在做什么,但是python为什么要这样做-即返回值而不是True / False?

10 and 7-2

返回5。同样,将和更改为或将导致功能更改。所以

10 or 7 - 2

将返回10。

这是合法/可靠的风格,还是有任何陷阱?

I’m trying to learn python and came across some code that is nice and short but doesn’t totally make sense

the context was:

def fn(*args):
    return len(args) and max(args)-min(args)

I get what it’s doing, but why does python do this – ie return the value rather than True/False?

10 and 7-2

returns 5. Similarly, changing the and to or will result in a change in functionality. So

10 or 7 - 2

Would return 10.

Is this legit/reliable style, or are there any gotchas on this?


回答 0

TL; DR

我们首先总结两个逻辑运算符and和的两个行为or。这些习语将构成我们下面讨论的基础。

and

如果有,则返回第一个Falsy值,否则返回表达式中的最后一个值。

or

如果有,则返回第一个Truthy值,否则返回表达式中的最后一个值。

行为也总结在docs中,尤其是在此表中:

无论其操作数如何,返回布尔值的唯一运算符是该not运算符。


“真实性”和“真实”评估

该声明

len(args) and max(args) - min(args)

是一种非常 Python式的简洁(并且可能可读性较低)的说法,即“如果args不为空,则返回结果max(args) - min(args)”,否则返回0。通常,它是if-else表达式的更简洁表示。例如,

exp1 and exp2

应该(大致)翻译为:

r1 = exp1
if r1:
    r1 = exp2

或者,等效地,

r1 = exp1 if exp1 else exp2

同样,

exp1 or exp2

相当于

r1 = exp1
if not r1:
    r1 = exp2

其中exp1exp2是任意的python对象,或返回某些对象的表达式。在这里理解逻辑andor运算符用法的关键是要理解它们不限于对布尔值进行操作或返回布尔值。任何具有真实性值的对象都可以在此处进行测试。这包括intstrlistdicttuplesetNoneType,和用户定义的对象。短路规则也同样适用。

但是什么是真实性?
它指的是在条件表达式中使用对象时如何求值。@Patrick Haugh在这篇文章中很好地总结了真实性。

除以下值“ falsy”外,所有值均被视为“真实”值:

  • None
  • False
  • 0
  • 0.0
  • 0j
  • Decimal(0)
  • Fraction(0, 1)
  • [] -一个空的 list
  • {} -一个空的 dict
  • () -一个空的 tuple
  • '' -一个空的 str
  • b'' -一个空的 bytes
  • set() -一个空的 set
  • 一个空的range,像range(0)
  • 为其对象
    • obj.__bool__() 退货 False
    • obj.__len__() 退货 0

“真实的”值将满足ifwhile 语句执行的检查。我们使用“真实的”和“虚假的”来区别 boolTrueFalse


如何and运作

我们以OP的问题为切入点,讨论在这些情况下如何操作这些运算符。

给定一个带有定义的函数

def foo(*args):
    ...

如何返回零个或多个参数列表中的最小值和最大值之间的差?

找到最小值和最大值很容易(使用内置函数!)。这里唯一的障碍是适当地处理参数列表可能为空的极端情况(例如,调用foo())。多亏and操作员,我们可以在一行中完成这两项操作:

def foo(*args):
     return len(args) and max(args) - min(args)

foo(1, 2, 3, 4, 5)
# 4

foo()
# 0

由于and使用,如果第二个表达式为,则也必须对其求值True。请注意,如果第一个表达式的值为真,则返回值始终第二个表达式的结果。如果第一个表达式的计算结果为Falsy,则返回的结果为第一个表达式的结果。

在上面的函数中,如果foo接收到一个或多个参数,len(args)则大于0(一个正数),因此返回的结果为max(args) - min(args)。OTOH,如果没有参数传递,len(args)0这是Falsy,并0返回。

请注意,编写此函数的另一种方法是:

def foo(*args):
    if not len(args):
        return 0

    return max(args) - min(args)

或者,更简而言之,

def foo(*args):
    return 0 if not args else max(args) - min(args)

当然,如果这些功能都不执行任何类型检查,那么除非您完全信任所提供的输入,否则不要依赖这些结构的简单性。


如何or运作

or用一个人为的例子以类似的方式解释了它的工作。

给定一个带有定义的函数

def foo(*args):
    ...

您将如何完成foo所有数字的归还9000

我们or这里用来处理拐角处的情况。我们定义foo为:

def foo(*args):
     return [x for x in args if x > 9000] or 'No number over 9000!'

foo(9004, 1, 2, 500)
# [9004]

foo(1, 2, 3, 4)
# 'No number over 9000!'

foo对列表执行过滤,以保留上的所有数字9000。如果存在任何这样的数字,则列表理解的结果是一个非空列表,该列表为Truthy,因此将其返回(此处发生短路)。如果不存在这样的数字,则list comp的结果[]为Falsy。因此,现在对第二个表达式求值(一个非空字符串)并返回。

使用条件,我们可以将该函数重写为:

def foo(*args):
    r = [x for x in args if x > 9000]
    if not r:
        return 'No number over 9000!' 

    return r

和以前一样,此结构在错误处理方面更加灵活。

TL;DR

We start by summarising the two behaviour of the two logical operators and and or. These idioms will form the basis of our discussion below.

and

Return the first Falsy value if there are any, else return the last value in the expression.

or

Return the first Truthy value if there are any, else return the last value in the expression.

The behaviour is also summarised in the docs, especially in this table:

The only operator returning a boolean value regardless of its operands is the not operator.


“Truthiness”, and “Truthy” Evaluations

The statement

len(args) and max(args) - min(args)

Is a very pythonic concise (and arguably less readable) way of saying “if args is not empty, return the result of max(args) - min(args)“, otherwise return 0. In general, it is a more concise representation of an if-else expression. For example,

exp1 and exp2

Should (roughly) translate to:

r1 = exp1
if r1:
    r1 = exp2

Or, equivalently,

r1 = exp2 if exp1 else exp1

Similarly,

exp1 or exp2

Should (roughly) translate to:

r1 = exp1
if not r1:
    r1 = exp2

Or, equivalently,

r1 = exp1 if exp1 else exp2

Where exp1 and exp2 are arbitrary python objects, or expressions that return some object. The key to understanding the uses of the logical and and or operators here is understanding that they are not restricted to operating on, or returning boolean values. Any object with a truthiness value can be tested here. This includes int, str, list, dict, tuple, set, NoneType, and user defined objects. Short circuiting rules still apply as well.

But what is truthiness?
It refers to how objects are evaluated when used in conditional expressions. @Patrick Haugh summarises truthiness nicely in this post.

All values are considered “truthy” except for the following, which are “falsy”:

  • None
  • False
  • 0
  • 0.0
  • 0j
  • Decimal(0)
  • Fraction(0, 1)
  • [] – an empty list
  • {} – an empty dict
  • () – an empty tuple
  • '' – an empty str
  • b'' – an empty bytes
  • set() – an empty set
  • an empty range, like range(0)
  • objects for which
    • obj.__bool__() returns False
    • obj.__len__() returns 0

A “truthy” value will satisfy the check performed by if or while statements. We use “truthy” and “falsy” to differentiate from the bool values True and False.


How and Works

We build on OP’s question as a segue into a discussion on how these operators in these instances.

Given a function with the definition

def foo(*args):
    ...

How do I return the difference between the minimum and maximum value in a list of zero or more arguments?

Finding the minimum and maximum is easy (use the inbuilt functions!). The only snag here is appropriately handling the corner case where the argument list could be empty (for example, calling foo()). We can do both in a single line thanks to the and operator:

def foo(*args):
     return len(args) and max(args) - min(args)
foo(1, 2, 3, 4, 5)
# 4

foo()
# 0

Since and is used, the second expression must also be evaluated if the first is True. Note that, if the first expression is evaluated to be truthy, the return value is always the result of the second expression. If the first expression is evaluated to be Falsy, then the result returned is the result of the first expression.

In the function above, If foo receives one or more arguments, len(args) is greater than 0 (a positive number), so the result returned is max(args) - min(args). OTOH, if no arguments are passed, len(args) is 0 which is Falsy, and 0 is returned.

Note that an alternative way to write this function would be:

def foo(*args):
    if not len(args):
        return 0
    
    return max(args) - min(args)

Or, more concisely,

def foo(*args):
    return 0 if not args else max(args) - min(args)

If course, none of these functions perform any type checking, so unless you completely trust the input provided, do not rely on the simplicity of these constructs.


How or Works

I explain the working of or in a similar fashion with a contrived example.

Given a function with the definition

def foo(*args):
    ...

How would you complete foo to return all numbers over 9000?

We use or to handle the corner case here. We define foo as:

def foo(*args):
     return [x for x in args if x > 9000] or 'No number over 9000!'

foo(9004, 1, 2, 500)
# [9004]

foo(1, 2, 3, 4)
# 'No number over 9000!'

foo performs a filtration on the list to retain all numbers over 9000. If there exist any such numbers, the result of the list comprehension is a non-empty list which is Truthy, so it is returned (short circuiting in action here). If there exist no such numbers, then the result of the list comp is [] which is Falsy. So the second expression is now evaluated (a non-empty string) and is returned.

Using conditionals, we could re-write this function as,

def foo(*args):
    r = [x for x in args if x > 9000]
    if not r:
        return 'No number over 9000!' 
    
    return r

As before, this structure is more flexible in terms of error handling.


回答 1

Python Docs报价

注意,既不and也不or 限制它们返回到和的类型,而是返回最后一个求值的参数。有时这很有用,例如,如果为空则应替换为默认值的字符串,则表达式会产生所需的值。FalseTruess or 'foo'

因此,这就是设计Python评估布尔表达式的方式,并且上述文档使我们了解了为什么要这样做。

要获得布尔值,只需对其进行类型转换。

return bool(len(args) and max(args)-min(args))

为什么?

短路。

例如:

2 and 3 # Returns 3 because 2 is Truthy so it has to check 3 too
0 and 3 # Returns 0 because 0 is Falsey and there's no need to check 3 at all

同样or也是如此,也就是说,它将在找到表达式后立即返回Truthy表达式,因为评估表达式的其余部分是多余的。

而不是返回铁杆True或者False,Python的回报TruthyFalsey,这是无论如何要评估为TrueFalse。您可以按原样使用该表达式,它将仍然有效。


要知道什么是TruthyFalsey,检查帕特里克·哈夫的答案

Quoting from Python Docs

Note that neither and nor or restrict the value and type they return to False and True, but rather return the last evaluated argument. This is sometimes useful, e.g., if s is a string that should be replaced by a default value if it is empty, the expression s or 'foo' yields the desired value.

So, this is how Python was designed to evaluate the boolean expressions and the above documentation gives us an insight of why they did it so.

To get a boolean value just typecast it.

return bool(len(args) and max(args)-min(args))

Why?

Short-circuiting.

For example:

2 and 3 # Returns 3 because 2 is Truthy so it has to check 3 too
0 and 3 # Returns 0 because 0 is Falsey and there's no need to check 3 at all

The same goes for or too, that is, it will return the expression which is Truthy as soon as it finds it, cause evaluating the rest of the expression is redundant.

Instead of returning hardcore True or False, Python returns Truthy or Falsey, which are anyway going to evaluate to True or False. You could use the expression as is, and it will still work.


To know what’s Truthy and Falsey, check Patrick Haugh’s answer


回答 2

执行布尔逻辑,但它们在比较时返回实际值之一。使用和时,值在布尔上下文中从左到右求值。0,”,[],(),{}None在布尔上下文中为false;其他一切都是真的。

如果所有的值在布尔上下文是真实的,并且返回最后一个值。

>>> 2 and 5
5
>>> 2 and 5 and 10
10

如果任何值在布尔上下文中为false ,则返回第一个false值。

>>> '' and 5
''
>>> 2 and 0 and 5
0

所以代码

return len(args) and max(args)-min(args)

返回max(args)-min(args)存在args时的值, 否则返回len(args)0。

and and or perform boolean logic, but they return one of the actual values when they are comparing. When using and, values are evaluated in a boolean context from left to right. 0, ”, [], (), {}, and None are false in a boolean context; everything else is true.

If all values are true in a boolean context, and returns the last value.

>>> 2 and 5
5
>>> 2 and 5 and 10
10

If any value is false in a boolean context and returns the first false value.

>>> '' and 5
''
>>> 2 and 0 and 5
0

So the code

return len(args) and max(args)-min(args)

returns the value of max(args)-min(args) when there is args else it returns len(args) which is 0.


回答 3

这是合法/可靠的风格,还是有任何陷阱?

这是合法的,这是短路评估,返回最后一个值。

您提供了一个很好的例子。0如果不传递任何参数,该函数将返回,并且代码不必检查是否传递无参数的特殊情况。

使用此方法的另一种方法是将None参数默认设置为可变基元,例如空列表:

def fn(alist=None):
    alist = alist or []
    ....

如果将一些非真实的值传递给alist它,则默认为空列表,这是避免if语句和可变的默认参数陷阱的便捷方法

Is this legit/reliable style, or are there any gotchas on this?

This is legit, it is a short circuit evaluation where the last value is returned.

You provide a good example. The function will return 0 if no arguments are passed, and the code doesn’t have to check for a special case of no arguments passed.

Another way to use this, is to default None arguments to a mutable primitive, like an empty list:

def fn(alist=None):
    alist = alist or []
    ....

If some non-truthy value is passed to alist it defaults to an empty list, handy way to avoid an if statement and the mutable default argument pitfall


回答 4

陷阱

是的,有一些陷阱。

fn() == fn(3) == fn(4, 4)

首先,如果fnreturn 0,则无法知道是否在没有任何参数,一个参数或多个相等参数的情况下调用它:

>>> fn()
0
>>> fn(3)
0
>>> fn(3, 3, 3)
0

什么fn意思

那么,Python是一种动态语言。在任何地方都没有指定它的fn作用,输入应为什么以及输出应为什么样。因此,正确命名函数真的很重要。同样,不必调用参数argsdelta(*numbers)或者calculate_range(*numbers)可以更好地描述该功能应该做什么。

参数错误

最后,and如果没有任何参数调用逻辑运算符,则可以防止该函数失败。但是,如果某些参数不是数字,它将仍然失败:

>>> fn('1')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, in fn
TypeError: unsupported operand type(s) for -: 'str' and 'str'
>>> fn(1, '2')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, in fn
TypeError: '>' not supported between instances of 'str' and 'int'
>>> fn('a', 'b')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, in fn
TypeError: unsupported operand type(s) for -: 'str' and 'str'

可能的选择

这是一种根据“比请求更容易获得宽恕”来编写函数的方法原理

def delta(*numbers):
    try:
        return max(numbers) - min(numbers)
    except TypeError:
        raise ValueError("delta should only be called with numerical arguments") from None
    except ValueError:
        raise ValueError("delta should be called with at least one numerical argument") from None

举个例子:

>>> delta()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 7, in delta
ValueError: delta should be called with at least one numerical argument
>>> delta(3)
0
>>> delta('a')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 5, in delta
ValueError: delta should only be called with numerical arguments
>>> delta('a', 'b')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 5, in delta
ValueError: delta should only be called with numerical arguments
>>> delta('a', 3)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 5, in delta
ValueError: delta should only be called with numerical arguments
>>> delta(3, 4.5)
1.5
>>> delta(3, 5, 7, 2)
5

如果您确实不希望在delta不带任何参数的情况下被调用时引发异常,则可以返回一些否则无法实现的值(例如-1None):

>>> def delta(*numbers):
...     try:
...         return max(numbers) - min(numbers)
...     except TypeError:
...         raise ValueError("delta should only be called with numerical arguments") from None
...     except ValueError:
...         return -1 # or None
... 
>>> 
>>> delta()
-1

Gotchas

Yes, there are a few gotchas.

fn() == fn(3) == fn(4, 4)

First, if fn returns 0, you cannot know if it was called without any parameter, with one parameter or with multiple, equal parameters :

>>> fn()
0
>>> fn(3)
0
>>> fn(3, 3, 3)
0

What does fn mean?

Then, Python is a dynamic language. It’s not specified anywhere what fn does, what its input should be and what its output should look like. Therefore, it’s really important to name the function correctly. Similarly, arguments don’t have to be called args. delta(*numbers) or calculate_range(*numbers) might describe better what the function is supposed to do.

Argument errors

Finally, the logical and operator is supposed to prevent the function to fail if called without any argument. It still fails if some argument isn’t a number, though:

>>> fn('1')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, in fn
TypeError: unsupported operand type(s) for -: 'str' and 'str'
>>> fn(1, '2')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, in fn
TypeError: '>' not supported between instances of 'str' and 'int'
>>> fn('a', 'b')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, in fn
TypeError: unsupported operand type(s) for -: 'str' and 'str'

Possible alternative

Here’s a way to write the function according to the “Easier to ask for forgiveness than permission.” principle:

def delta(*numbers):
    try:
        return max(numbers) - min(numbers)
    except TypeError:
        raise ValueError("delta should only be called with numerical arguments") from None
    except ValueError:
        raise ValueError("delta should be called with at least one numerical argument") from None

As an example:

>>> delta()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 7, in delta
ValueError: delta should be called with at least one numerical argument
>>> delta(3)
0
>>> delta('a')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 5, in delta
ValueError: delta should only be called with numerical arguments
>>> delta('a', 'b')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 5, in delta
ValueError: delta should only be called with numerical arguments
>>> delta('a', 3)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 5, in delta
ValueError: delta should only be called with numerical arguments
>>> delta(3, 4.5)
1.5
>>> delta(3, 5, 7, 2)
5

If you really don’t want to raise an exception when delta is called without any argument, you could return some value which cannot be possible otherwise (e.g. -1 or None):

>>> def delta(*numbers):
...     try:
...         return max(numbers) - min(numbers)
...     except TypeError:
...         raise ValueError("delta should only be called with numerical arguments") from None
...     except ValueError:
...         return -1 # or None
... 
>>> 
>>> delta()
-1

回答 5

这是合法/可靠的风格,还是有任何陷阱?

我想补充一下这个问题,它不仅合法可靠,而且非常实用。这是一个简单的示例:

>>>example_list = []
>>>print example_list or 'empty list'
empty list

因此,您可以真正利用它来发挥自己的优势。为了简明扼要,这是我的看法:

Or 算子

Python的or运算符返回第一个Truth-y值或最后一个值,然后停止

And 算子

Python的and运算符返回第一个False-y值或最后一个值,然后停止

幕后花絮

在python中,所有数字都被解释True为0以外的数字。因此,请说:

0 and 10 

是相同的:

False and True

这显然是False。因此,逻辑上返回0

Is this legit/reliable style, or are there any gotchas on this?

I would like to add to this question that it not only legit and reliable but it also ultra practical. Here is a simple example:

>>>example_list = []
>>>print example_list or 'empty list'
empty list

Therefore you can really use it at your advantage. In order to be conscise this is how I see it:

Or operator

Python’s or operator returns the first Truth-y value, or the last value, and stops

And operator

Python’s and operator returns the first False-y value, or the last value, and stops

Behind the scenes

In python, all numbers are interpreted as True except for 0. Therefore, saying:

0 and 10 

is the same as:

False and True

Which is clearly False. It is therefore logical that it returns 0


回答 6

是。这是和比较的正确行为。

至少在Python,A and B返回B如果A基本上True包括:如果A不为空,NOT None不是空的容器(如一个空的listdict等)。A返回的IFF A本质上是Falseor None或Empty或Null。

在另一方面,A or B返回A如果A基本上True包括:如果A不为空,NOT None不是空的容器(如一个空的listdict等),否则返回B

不容易注意到(或忽略)此行为,因为在Python中,任何non-null非空对象的求值为True都被视为布尔值。

例如,以下所有内容将打印“ True”

if [102]: 
    print "True"
else: 
    print "False"

if "anything that is not empty or None": 
    print "True"
else: 
    print "False"

if {1, 2, 3}: 
    print "True"
else: 
    print "False"

另一方面,以下所有内容将打印“ False”

if []: 
    print "True"
else: 
    print "False"

if "": 
    print "True"
else: 
    print "False"

if set ([]): 
    print "True"
else: 
    print "False"

Yes. This is the correct behaviour of and comparison.

At least in Python, A and B returns B if A is essentially True including if A is NOT Null, NOT None NOT an Empty container (such as an empty list, dict, etc). A is returned IFF A is essentially False or None or Empty or Null.

On the other hand, A or B returns A if A is essentially True including if A is NOT Null, NOT None NOT an Empty container (such as an empty list, dict, etc), otherwise it returns B.

It is easy to not notice (or to overlook) this behaviour because, in Python, any non-null non-empty object evaluates to True is treated like a boolean.

For example, all the following will print “True”

if [102]: 
    print "True"
else: 
    print "False"

if "anything that is not empty or None": 
    print "True"
else: 
    print "False"

if {1, 2, 3}: 
    print "True"
else: 
    print "False"

On the other hand, all the following will print “False”

if []: 
    print "True"
else: 
    print "False"

if "": 
    print "True"
else: 
    print "False"

if set ([]): 
    print "True"
else: 
    print "False"

回答 7

以简单的方式理解

与: if first_val is False return first_val else second_value

例如:

1 and 2 # here it will return 2 because 1 is not False

但,

0 and 2 # will return 0 because first value is 0 i.e False

=>如果任何人为假,它将为假。如果两个都成立,那么只有它会成立

要么 : if first_val is False return second_val else first_value

原因是,如果first为false,则检查2是否为true。

例如:

1 or 2 # here it will return 1 because 1 is not False

但,

0 or 2 # will return 2 because first value is 0 i.e False

或=>如果任何人为假,则为true。因此,如果第一个值是假,那么无论假设哪个是2值。因此它会返回第二个值。

如果任何人是真实的,那么它将成为真实。如果两者均为假,那么它将变为假。

to understand in simple way,

AND : if first_val is False return first_val else second_value

eg:

1 and 2 # here it will return 2 because 1 is not False

but,

0 and 2 # will return 0 because first value is 0 i.e False

and => if anyone false, it will be false. if both are true then only it will become true

OR : if first_val is False return second_val else first_value

reason is, if first is false it check whether 2 is true or not.

eg:

1 or 2 # here it will return 1 because 1 is not False

but,

0 or 2 # will return 2 because first value is 0 i.e False

or => if anyone false, it will be true. so if first value is false no matter what 2 value suppose to be. so it returns second value what ever it can be.

if anyone is true then it will become true. if both are false then it will become false.


在if语句中,Python等效于&&(逻辑与)

问题:在if语句中,Python等效于&&(逻辑与)

这是我的代码:

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条件中遇到错误。
我究竟做错了什么?

Here’s my code:

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

I’m getting an error in the IF conditional.
What am I doing wrong?


回答 0

您可能想要and而不是&&

You would want and instead of &&.


回答 1

Python使用andor条件。

if foo == 'abc' and bar == 'bac' or zoo == '123':
  # do something

Python uses and and or conditionals.

i.e.

if foo == 'abc' and bar == 'bac' or zoo == '123':
  # do something

回答 2

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

得到a的原因SyntaxError&&Python中没有运算符。同样||!并且不是有效的 Python运算符。

您可能从其他语言中了解到的某些运算符在Python中使用不同的名称。逻辑运算符&&||实际上被称为andor。同样,逻辑否定运算符!称为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。二进制算术运算

逻辑运算符(像许多其他语言一样)具有使它们短路的优点。这意味着,如果第一个操作数已经定义了结果,则根本不会对第二个运算符求值。

为了说明这一点,我使用了一个简单地使用值的函数,将其打印并再次返回。方便查看由于print语句而实际评估的内容:

>>> 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

总结一下,这是另一个表:

+-----------------+-------------------------+
|   Expression    |  Right side evaluated?  |
+=================+=========================+
| `True` and ...  |           Yes           |
+-----------------+-------------------------+
| `False` and ... |           No            |
+-----------------+-------------------------+
|  `True` or ...  |           No            |
+-----------------+-------------------------+
| `False` or ...  |           Yes           |
+-----------------+-------------------------+

TrueFalse代表什么bool(left-hand-side)回报,他们不必是TrueFalse,他们只需要返回TrueFalsebool被要求他们(1)。

因此,在Pseudo-Code(!)中,andand 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调用可用于自定义您的类的行为有andornot

为了说明如何进行自定义,我使用该类来再次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结果。因此,这些要点可能与您无关。

I’m getting an error in the IF conditional. What am I doing wrong?

There reason that you get a SyntaxError is that there is no && operator in Python. Likewise || and ! are not valid Python operators.

Some of the operators you may know from other languages have a different name in Python. The logical operators && and || are actually called and and or. Likewise the logical negation operator ! is called not.

So you could just write:

if len(a) % 2 == 0 and len(b) % 2 == 0:

or even:

if not (len(a) % 2 or len(b) % 2):

Some additional information (that might come in handy):

I summarized the operator “equivalents” in this table:

+------------------------------+---------------------+
|  Operator (other languages)  |  Operator (Python)  |
+==============================+=====================+
|              &&              |         and         |
+------------------------------+---------------------+
|              ||              |         or          |
+------------------------------+---------------------+
|              !               |         not         |
+------------------------------+---------------------+

See also Python documentation: 6.11. Boolean operations.

Besides the logical operators Python also has bitwise/binary operators:

+--------------------+--------------------+
|  Logical operator  |  Bitwise operator  |
+====================+====================+
|        and         |         &          |
+--------------------+--------------------+
|         or         |         |          |
+--------------------+--------------------+

There is no bitwise negation in Python (just the bitwise inverse operator ~ – but that is not equivalent to not).

See also 6.6. Unary arithmetic and bitwise/binary operations and 6.7. Binary arithmetic operations.

The logical operators (like in many other languages) have the advantage that these are short-circuited. That means if the first operand already defines the result, then the second operator isn’t evaluated at all.

To show this I use a function that simply takes a value, prints it and returns it again. This is handy to see what is actually evaluated because of the print statements:

>>> def print_and_return(value):
...     print(value)
...     return value

>>> res = print_and_return(False) and print_and_return(True)
False

As you can see only one print statement is executed, so Python really didn’t even look at the right operand.

This is not the case for the binary operators. Those always evaluate both operands:

>>> res = print_and_return(False) & print_and_return(True);
False
True

But if the first operand isn’t enough then, of course, the second operator is evaluated:

>>> res = print_and_return(True) and print_and_return(False);
True
False

To summarize this here is another Table:

+-----------------+-------------------------+
|   Expression    |  Right side evaluated?  |
+=================+=========================+
| `True` and ...  |           Yes           |
+-----------------+-------------------------+
| `False` and ... |           No            |
+-----------------+-------------------------+
|  `True` or ...  |           No            |
+-----------------+-------------------------+
| `False` or ...  |           Yes           |
+-----------------+-------------------------+

The True and False represent what bool(left-hand-side) returns, they don’t have to be True or False, they just need to return True or False when bool is called on them (1).

So in Pseudo-Code(!) the and and or functions work like these:

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)

Note that this is pseudo-code not Python code. In Python you cannot create functions called and or or because these are keywords. Also you should never use “evaluate” or if bool(...).

Customizing the behavior of your own classes

This implicit bool call can be used to customize how your classes behave with and, or and not.

To show how this can be customized I use this class which again prints something to track what is happening:

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)

So let’s see what happens with that class in combination with these operators:

>>> 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)

If you don’t have a __bool__ method then Python also checks if the object has a __len__ method and if it returns a value greater than zero. That might be useful to know in case you create a sequence container.

See also 4.1. Truth Value Testing.

NumPy arrays and subclasses

Probably a bit beyond the scope of the original question but in case you’re dealing with NumPy arrays or subclasses (like Pandas Series or DataFrames) then the implicit bool call will raise the dreaded 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().

In these cases you can use the logical and function from NumPy which performs an element-wise and (or 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])

If you’re dealing just with boolean arrays you could also use the binary operators with NumPy, these do perform element-wise (but also binary) comparisons:

>>> 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)

That the bool call on the operands has to return True or False isn’t completely correct. It’s just the first operand that needs to return a boolean in it’s __bool__ method:

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)

That’s because and actually returns the first operand if the first operand evaluates to False and if it evaluates to True then it returns the second operand:

>>> x1
Test(10)
>>> x2
Test(False)

Similarly for or but just the other way around:

>>> Test(True) or Test(10)
Test(True)
>>> Test(False) or Test(10)
Test(10)

However if you use them in an if statement the if will also implicitly call bool on the result. So these finer points may not be relevant for you.


回答 3

两条评论:

  • 在Python中使用andor进行逻辑操作。
  • 使用4个空格而不是2缩进。您稍后将感谢自己,因为您的代码看起来与其他人的代码几乎相同。有关更多详细信息,请参见PEP 8

Two comments:

  • Use and and or for logical operations in Python.
  • Use 4 spaces to indent instead of 2. You will thank yourself later because your code will look pretty much the same as everyone else’s code. See PEP 8 for more details.

回答 4

您可以使用andor执行类似C,C ++的逻辑操作。就像字面上的andis &&oris一样||


看看这个有趣的例子,

假设您要使用Python构建Logic Gate:

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

希望这可以帮助!

You use and and or to perform logical operations like in C, C++. Like literally and is && and or is ||.


Take a look at this fun example,

Say you want to build Logic Gates in Python:

def AND(a,b):
    return (a and b) #using and operator

def OR(a,b):
    return (a or b)  #using or operator

Now try calling them:

print AND(False, False)
print OR(True, False)

This will output:

False
True

Hope this helps!


回答 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:]

I went with a purlely mathematical solution:

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

可能这不是执行此任务的最佳代码,但是可以正常工作-

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:]

Probably this is not best code for this task, but is working –

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:]

回答 7

一个&(而不是double &&)就足够了,或者作为最高答案建议您可以使用’and’。我也在大熊猫中发现了

cities['Is wide and has saint name'] = (cities['Population'] > 1000000) 
& cities['City name'].apply(lambda name: name.startswith('San'))

如果我们将“&”替换为“ and”,则将无法使用。

A single & (not double &&) is enough or as the top answer suggests you can use ‘and’. I also found this in pandas

cities['Is wide and has saint name'] = (cities['Population'] > 1000000) 
& cities['City name'].apply(lambda name: name.startswith('San'))

if we replace the “&” with “and”, it won’t work.


回答 8

也许用&代替%可以更快并保持可读性

其他测试奇数/奇数

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

maybe with & instead % is more fast and mantain readibility

other tests even/odd

x is even ? x % 2 == 0

x is odd ? not x % 2 == 0

maybe is more clear with bitwise and 1

x is odd ? x & 1

x is even ? not x & 1 (not odd)

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

回答 9

有条件地使用“和”。在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

Use of “and” in conditional. I often use this when importing in 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

如何在Python中获得两个变量的逻辑异或?

问题:如何在Python中获得两个变量的逻辑异或?

如何在Python中获得两个变量的逻辑异或?

例如,我有两个期望是字符串的变量。我想测试其中只有一个包含True值(不是None或空字符串):

str1 = raw_input("Enter string one:")
str2 = raw_input("Enter string two:")
if logical_xor(str1, str2):
    print "ok"
else:
    print "bad"

^运营商似乎是按位,并在所有对象没有定义:

>>> 1 ^ 1
0
>>> 2 ^ 1
3
>>> "abc" ^ ""
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for ^: 'str' and 'str'

How do you get the logical xor of two variables in Python?

For example, I have two variables that I expect to be strings. I want to test that only one of them contains a True value (is not None or the empty string):

str1 = raw_input("Enter string one:")
str2 = raw_input("Enter string two:")
if logical_xor(str1, str2):
    print "ok"
else:
    print "bad"

The ^ operator seems to be bitwise, and not defined on all objects:

>>> 1 ^ 1
0
>>> 2 ^ 1
3
>>> "abc" ^ ""
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for ^: 'str' and 'str'

回答 0

如果您已经将输入归一化为布尔值,则!=为xor。

bool(a) != bool(b)

If you’re already normalizing the inputs to booleans, then != is xor.

bool(a) != bool(b)

回答 1

您始终可以使用xor的定义从其他逻辑运算中进行计算:

(a and not b) or (not a and b)

但这对我来说太冗长了,乍一看并不清楚。另一种方法是:

bool(a) ^ bool(b)

两个布尔值的xor运算符是逻辑xor(与ints不同,在ints上是按位的)。这是有道理的,因为bool它只是的子类int,但是被实现为仅具有01。当域限制为0和时,逻辑异或等效于按位异或1

因此,该logical_xor功能将实现为:

def logical_xor(str1, str2):
    return bool(str1) ^ bool(str2)

感谢尼克·科格伦了Python-3000的邮件列表上

You can always use the definition of xor to compute it from other logical operations:

(a and not b) or (not a and b)

But this is a little too verbose for me, and isn’t particularly clear at first glance. Another way to do it is:

bool(a) ^ bool(b)

The xor operator on two booleans is logical xor (unlike on ints, where it’s bitwise). Which makes sense, since bool is just a subclass of int, but is implemented to only have the values 0 and 1. And logical xor is equivalent to bitwise xor when the domain is restricted to 0 and 1.

So the logical_xor function would be implemented like:

def logical_xor(str1, str2):
    return bool(str1) ^ bool(str2)

Credit to Nick Coghlan on the Python-3000 mailing list.


回答 2

operator模块(与^运算符相同)中,Python内置了按位异或运算符:

from operator import xor
xor(bool(a), bool(b))  # Note: converting to bools is essential

Bitwise exclusive-or is already built-in to Python, in the operator module (which is identical to the ^ operator):

from operator import xor
xor(bool(a), bool(b))  # Note: converting to bools is essential

回答 3

正如Zach解释的那样,您可以使用:

xor = bool(a) ^ bool(b)

就个人而言,我赞成略有不同的方言:

xor = bool(a) + bool(b) == 1

该方言的灵感来自我在学校学习的一种逻辑图表语言,其中“ OR”由包含≥1(大于或等于1)的框表示,而“ XOR”由包含的框表示=1

这具有正确实现互斥或在多个操作数上的优势。

  • “ 1 = a ^ b ^ c …”表示真实操作数的数量为奇数。此运算符是“奇偶校验”。
  • “ 1 = a + b + c …”表示恰好一个操作数为真。这是“排他性或”,意思是“一个排除其他”。

As Zach explained, you can use:

xor = bool(a) ^ bool(b)

Personally, I favor a slightly different dialect:

xor = bool(a) + bool(b) == 1

This dialect is inspired from a logical diagramming language I learned in school where “OR” was denoted by a box containing ≥1 (greater than or equal to 1) and “XOR” was denoted by a box containing =1.

This has the advantage of correctly implementing exclusive or on multiple operands.

  • “1 = a ^ b ^ c…” means the number of true operands is odd. This operator is “parity”.
  • “1 = a + b + c…” means exactly one operand is true. This is “exclusive or”, meaning “one to the exclusion of the others”.

回答 4

  • Python的逻辑orA or B:回报A,如果bool(A)True,否则返回B
  • Python的逻辑andA and B:回报A,如果bool(A)False,否则返回B

为了保持大多数思维方式,我的逻辑异或定义为:

def logical_xor(a, b):
    if bool(a) == bool(b):
        return False
    else:
        return a or b

这样,它可以返回abFalse

>>> logical_xor('this', 'that')
False
>>> logical_xor('', '')
False
>>> logical_xor('this', '')
'this'
>>> logical_xor('', 'that')
'that'
  • Python logical or: A or B: returns A if bool(A) is True, otherwise returns B
  • Python logical and: A and B: returns A if bool(A) is False, otherwise returns B

To keep most of that way of thinking, my logical xor definintion would be:

def logical_xor(a, b):
    if bool(a) == bool(b):
        return False
    else:
        return a or b

That way it can return a, b, or False:

>>> logical_xor('this', 'that')
False
>>> logical_xor('', '')
False
>>> logical_xor('this', '')
'this'
>>> logical_xor('', 'that')
'that'

回答 5

我已经测试了几种方法,并且not a != (not b)似乎是最快的。

这是一些测试

%timeit not a != (not b)
10000000 loops, best of 3: 78.5 ns per loop

%timeit bool(a) != bool(b)
1000000 loops, best of 3: 343 ns per loop

%timeit not a ^ (not b)
10000000 loops, best of 3: 131 ns per loop

编辑: 上面的示例1和3缺少括号,因此结果不正确。新结果+ truth()具有ShadowRanger建议的功能。

%timeit  (not a) ^  (not b)   # 47 ns
%timeit  (not a) != (not b)   # 44.7 ns
%timeit truth(a) != truth(b)  # 116 ns
%timeit  bool(a) != bool(b)   # 190 ns

I’ve tested several approaches and not a != (not b) appeared to be the fastest.

Here are some tests

%timeit not a != (not b)
10000000 loops, best of 3: 78.5 ns per loop

%timeit bool(a) != bool(b)
1000000 loops, best of 3: 343 ns per loop

%timeit not a ^ (not b)
10000000 loops, best of 3: 131 ns per loop

Edit: Examples 1 and 3 above are missing parenthes so result is incorrect. New results + truth() function as ShadowRanger suggested.

%timeit  (not a) ^  (not b)   # 47 ns
%timeit  (not a) != (not b)   # 44.7 ns
%timeit truth(a) != truth(b)  # 116 ns
%timeit  bool(a) != bool(b)   # 190 ns

回答 6

奖励线程:

提议者的想法…尝试(可能是)python表达式“不是”以便获得逻辑“异或”的行为

真值表将是:

>>> True is not True
False
>>> True is not False
True
>>> False is not True
True
>>> False is not False
False
>>>

对于您的示例字符串:

>>> "abc" is not  ""
True
>>> 'abc' is not 'abc' 
False
>>> 'abc' is not '' 
True
>>> '' is not 'abc' 
True
>>> '' is not '' 
False
>>> 

然而; 正如上面所指出的,这取决于您想对任何几个字符串进行抽出的实际行为,因为字符串不是布尔值……甚至更多:如果您“深入Python”,您会发现“和”和“或”» http://www.diveintopython.net/power_of_introspection/and_or.html

对不起,我写的英语不是我的母语。

问候。

Rewarding thread:

Anoder idea… Just you try the (may be) pythonic expression «is not» in order to get behavior of logical «xor»

The truth table would be:

>>> True is not True
False
>>> True is not False
True
>>> False is not True
True
>>> False is not False
False
>>>

And for your example string:

>>> "abc" is not  ""
True
>>> 'abc' is not 'abc' 
False
>>> 'abc' is not '' 
True
>>> '' is not 'abc' 
True
>>> '' is not '' 
False
>>> 

However; as they indicated above, it depends of the actual behavior you want to pull out about any couple strings, because strings aren’t boleans… and even more: if you «Dive Into Python» you will find «The Peculiar Nature of “and” and “or”» http://www.diveintopython.net/power_of_introspection/and_or.html

Sorry my writed English, it’s not my born language.

Regards.


回答 7

Python具有按位异或运算符,它是^

>>> True ^ False
True
>>> True ^ True
False
>>> False ^ True
True
>>> False ^ False
False

您可以通过在应用xor(^)之前将输入转换为布尔值来使用它:

bool(a) ^ bool(b)

(编辑-感谢Arel)

Python has a bitwise exclusive-OR operator, it’s ^:

>>> True ^ False
True
>>> True ^ True
False
>>> False ^ True
True
>>> False ^ False
False

You can use it by converting the inputs to booleans before applying xor (^):

bool(a) ^ bool(b)

(Edited – thanks Arel)


回答 8

因为我看不到使用变量参数的xor的简单变体,而仅对True值True或False进行运算,所以我将它扔在这里供任何人使用。正如其他人所指出的那样,很简单(不是很清楚)。

def xor(*vars):
    sum = False
    for v in vars:
        sum = sum ^ bool(v)
    return sum

使用也很简单:

if xor(False, False, True, False):
    print "Hello World!"

由于这是广义的n元逻辑XOR,因此每当True操作数的数量为奇数时,它的真值将为True(不仅只有当一个为True时,这才是n元XOR为True的一种情况)。

因此,如果您要搜索仅在其中一个操作数正好存在时才为True的n元谓词,则可能需要使用:

def isOne(*vars):
    sum = False
    for v in vars:
        if sum and v:
            return False
        else:
            sum = sum or v
    return sum

As I don’t see the simple variant of xor using variable arguments and only operation on Truth values True or False, I’ll just throw it here for anyone to use. It’s as noted by others, pretty (not to say very) straightforward.

def xor(*vars):
    sum = False
    for v in vars:
        sum = sum ^ bool(v)
    return sum

And usage is straightforward as well:

if xor(False, False, True, False):
    print "Hello World!"

As this is the generalized n-ary logical XOR, it’s truth value will be True whenever the number of True operands is odd (and not only when exactly one is True, this is just one case in which n-ary XOR is True).

Thus if you are in search of a n-ary predicate that is only True when exactly one of it’s operands is, you might want to use:

def isOne(*vars):
    sum = False
    for v in vars:
        if sum and v:
            return False
        else:
            sum = sum or v
    return sum

回答 9

异或定义如下

def xor( a, b ):
    return (a or b) and not (a and b)

Exclusive Or is defined as follows

def xor( a, b ):
    return (a or b) and not (a and b)

回答 10

有时我发现自己使用1和0代替布尔True和False值。在这种情况下,xor可以定义为

z = (x + y) % 2

它具有以下真值表:

     x
   |0|1|
  -+-+-+
  0|0|1|
y -+-+-+
  1|1|0|
  -+-+-+

Sometimes I find myself working with 1 and 0 instead of boolean True and False values. In this case xor can be defined as

z = (x + y) % 2

which has the following truth table:

     x
   |0|1|
  -+-+-+
  0|0|1|
y -+-+-+
  1|1|0|
  -+-+-+

回答 11

我知道这很晚了,但是我有一个想法,可能只是为了文档而已。也许这会起作用:np.abs(x-y)这个想法是

  1. 如果x = True = 1且y = False = 0,则结​​果为| 1-0 | = 1 = True
  2. 如果x = False = 0和y = False = 0,那么结果将是| 0-0 | = 0 = False
  3. 如果x = True = 1和y = True = 1,则结果为| 1-1 | = 0 = False
  4. 如果x = False = 0和y = True = 1,那么结果将是| 0-1 | = 1 = True

I know this is late, but I had a thought and it might be worth, just for documentation. Perhaps this would work:np.abs(x-y) The idea is that

  1. if x=True=1 and y=False=0 then the result would be |1-0|=1=True
  2. if x=False=0 and y=False=0 then the result would be |0-0|=0=False
  3. if x=True=1 and y=True=1 then the result would be |1-1|=0=False
  4. if x=False=0 and y=True=1 then the result would be |0-1|=1=True

回答 12

简单易懂:

sum( (bool(a), bool(b) ) == 1

如果您想要的是排他性选择,则可以将其扩展为多个参数:

sum( bool(x) for x in y ) % 2 == 1

Simple, easy to understand:

sum( (bool(a), bool(b) ) == 1

If an exclusive choice is what you’re after, it can be expanded to multiple arguments:

sum( bool(x) for x in y ) % 2 == 1

回答 13

这个怎么样?

(not b and a) or (not a and b)

会给a如果b是假的
会给会给b如果a是假的
会给False否则

或使用Python 2.5+三元表达式:

(False if a else b) if b else a

How about this?

(not b and a) or (not a and b)

will give a if b is false
will give b if a is false
will give False otherwise

Or with the Python 2.5+ ternary expression:

(False if a else b) if b else a

回答 14

在此建议的某些实现在某些情况下将导致对操作数的重复评估,这可能导致意外的副作用,因此必须避免。

这就是说,一个xor实现,无论是收益True还是False相当简单; 如果可能的话,返回一个操作数之一的技巧非常棘手,因为对于选择哪个操作数没有共识,尤其是当有两个以上的操作数时。例如,应该xor(None, -1, [], True)返回None[]还是False?我敢打赌,对于某些人来说,每个答案都是最直观的答案。

对于True或False结果,有多达五个可能的选择:返回第一个操作数(如果它与值中的最终结果匹配,否则为布尔值),返回第一个匹配项(如果至少存在一个,否则为布尔值),返回最后一个操作数(如果… else …),返回最后一个匹配项(如果… else …),或始终返回布尔值。总共有5 ** 2 = 25种口味xor

def xor(*operands, falsechoice = -2, truechoice = -2):
  """A single-evaluation, multi-operand, full-choice xor implementation
  falsechoice, truechoice: 0 = always bool, +/-1 = first/last operand, +/-2 = first/last match"""
  if not operands:
    raise TypeError('at least one operand expected')
  choices = [falsechoice, truechoice]
  matches = {}
  result = False
  first = True
  value = choice = None
  # avoid using index or slice since operands may be an infinite iterator
  for operand in operands:
    # evaluate each operand once only so as to avoid unintended side effects
    value = bool(operand)
    # the actual xor operation
    result ^= value
    # choice for the current operand, which may or may not match end result
    choice = choices[value]
    # if choice is last match;
    # or last operand and the current operand, in case it is last, matches result;
    # or first operand and the current operand is indeed first;
    # or first match and there hasn't been a match so far
    if choice < -1 or (choice == -1 and value == result) or (choice == 1 and first) or (choice > 1 and value not in matches):
      # store the current operand
      matches[value] = operand
    # next operand will no longer be first
    first = False
  # if choice for result is last operand, but they mismatch
  if (choices[result] == -1) and (result != value):
    return result
  else:
    # return the stored matching operand, if existing, else result as bool
    return matches.get(result, result)

testcases = [
  (-1, None, True, {None: None}, [], 'a'),
  (None, -1, {None: None}, 'a', []),
  (None, -1, True, {None: None}, 'a', []),
  (-1, None, {None: None}, [], 'a')]
choices = {-2: 'last match', -1: 'last operand', 0: 'always bool', 1: 'first operand', 2: 'first match'}
for c in testcases:
  print(c)
  for f in sorted(choices.keys()):
    for t in sorted(choices.keys()):
      x = xor(*c, falsechoice = f, truechoice = t)
      print('f: %d (%s)\tt: %d (%s)\tx: %s' % (f, choices[f], t, choices[t], x))
  print()

Some of the implementations suggested here will cause repeated evaluation of the operands in some cases, which may lead to unintended side effects and therefore must be avoided.

That said, a xor implementation that returns either True or False is fairly simple; one that returns one of the operands, if possible, is much trickier, because no consensus exists as to which operand should be the chosen one, especially when there are more than two operands. For instance, should xor(None, -1, [], True) return None, [] or False? I bet each answer appears to some people as the most intuitive one.

For either the True- or the False-result, there are as many as five possible choices: return first operand (if it matches end result in value, else boolean), return first match (if at least one exists, else boolean), return last operand (if … else …), return last match (if … else …), or always return boolean. Altogether, that’s 5 ** 2 = 25 flavors of xor.

def xor(*operands, falsechoice = -2, truechoice = -2):
  """A single-evaluation, multi-operand, full-choice xor implementation
  falsechoice, truechoice: 0 = always bool, +/-1 = first/last operand, +/-2 = first/last match"""
  if not operands:
    raise TypeError('at least one operand expected')
  choices = [falsechoice, truechoice]
  matches = {}
  result = False
  first = True
  value = choice = None
  # avoid using index or slice since operands may be an infinite iterator
  for operand in operands:
    # evaluate each operand once only so as to avoid unintended side effects
    value = bool(operand)
    # the actual xor operation
    result ^= value
    # choice for the current operand, which may or may not match end result
    choice = choices[value]
    # if choice is last match;
    # or last operand and the current operand, in case it is last, matches result;
    # or first operand and the current operand is indeed first;
    # or first match and there hasn't been a match so far
    if choice < -1 or (choice == -1 and value == result) or (choice == 1 and first) or (choice > 1 and value not in matches):
      # store the current operand
      matches[value] = operand
    # next operand will no longer be first
    first = False
  # if choice for result is last operand, but they mismatch
  if (choices[result] == -1) and (result != value):
    return result
  else:
    # return the stored matching operand, if existing, else result as bool
    return matches.get(result, result)

testcases = [
  (-1, None, True, {None: None}, [], 'a'),
  (None, -1, {None: None}, 'a', []),
  (None, -1, True, {None: None}, 'a', []),
  (-1, None, {None: None}, [], 'a')]
choices = {-2: 'last match', -1: 'last operand', 0: 'always bool', 1: 'first operand', 2: 'first match'}
for c in testcases:
  print(c)
  for f in sorted(choices.keys()):
    for t in sorted(choices.keys()):
      x = xor(*c, falsechoice = f, truechoice = t)
      print('f: %d (%s)\tt: %d (%s)\tx: %s' % (f, choices[f], t, choices[t], x))
  print()

回答 15

包括我自己在内的许多人都需要一个xor功能类似于n输入异或电路的函数,其中n是可变的。(请参阅https://en.wikipedia.org/wiki/XOR_gate)。下面的简单函数实现了这一点。

def xor(*args):
   """
   This function accepts an arbitrary number of input arguments, returning True
   if and only if bool() evaluates to True for an odd number of the input arguments.
   """

   return bool(sum(map(bool,args)) % 2)

I / O示例如下:

In [1]: xor(False, True)
Out[1]: True

In [2]: xor(True, True)
Out[2]: False

In [3]: xor(True, True, True)
Out[3]: True

Many folks, including myself, need an xor function that behaves like an n-input xor circuit, where n is variable. (See https://en.wikipedia.org/wiki/XOR_gate). The following simple function implements this.

def xor(*args):
   """
   This function accepts an arbitrary number of input arguments, returning True
   if and only if bool() evaluates to True for an odd number of the input arguments.
   """

   return bool(sum(map(bool,args)) % 2)

Sample I/O follows:

In [1]: xor(False, True)
Out[1]: True

In [2]: xor(True, True)
Out[2]: False

In [3]: xor(True, True, True)
Out[3]: True

回答 16

要在Python中获取两个或多个变量的逻辑异或:

  1. 将输入转换为布尔值
  2. 使用按位异^或运算符(或operator.xor

例如,

bool(a) ^ bool(b)

当您将输入转换为布尔值时,按位异或将变得逻辑异或。

请注意,可接受的答案是错误的: !=由于运算符链接的微妙之处,它与Python中的xor不同

例如,使用时,以下三个值的异或是错误的!=

True ^  False ^  False  # True, as expected of XOR
True != False != False  # False! Equivalent to `(True != False) and (False != False)`

(PS我尝试编辑接受的答案以包含此警告,但我的更改被拒绝。)

To get the logical xor of two or more variables in Python:

  1. Convert inputs to booleans
  2. Use the bitwise xor operator (^ or operator.xor)

For example,

bool(a) ^ bool(b)

When you convert the inputs to booleans, bitwise xor becomes logical xor.

Note that the accepted answer is wrong: != is not the same as xor in Python because of the subtlety of operator chaining.

For instance, the xor of the three values below is wrong when using !=:

True ^  False ^  False  # True, as expected of XOR
True != False != False  # False! Equivalent to `(True != False) and (False != False)`

(P.S. I tried editing the accepted answer to include this warning, but my change was rejected.)


回答 17

当您知道XOR的作用时,这很容易:

def logical_xor(a, b):
    return (a and not b) or (not a and b)

test_data = [
  [False, False],
  [False, True],
  [True, False],
  [True, True],
]

for a, b in test_data:
    print '%r xor %s = %r' % (a, b, logical_xor(a, b))

It’s easy when you know what XOR does:

def logical_xor(a, b):
    return (a and not b) or (not a and b)

test_data = [
  [False, False],
  [False, True],
  [True, False],
  [True, True],
]

for a, b in test_data:
    print '%r xor %s = %r' % (a, b, logical_xor(a, b))

回答 18

这将对两个(或多个)变量进行逻辑异或

str1 = raw_input("Enter string one:")
str2 = raw_input("Enter string two:")

any([str1, str2]) and not all([str1, str2])

这种设置的第一个问题是,它很可能遍历整个列表两次,并且至少会两次检查至少一个元素。因此,它可能会提高代码的理解能力,但并不能提高速度(根据您的使用情况而可能有所不同)。

此设置的第二个问题是,无论变量数量如何,它都会检查排他性。乍一看,这可能是一个功能,但是随着变量数量的增加(如果有的话),第一个问题变得更加重要。

This gets the logical exclusive XOR for two (or more) variables

str1 = raw_input("Enter string one:")
str2 = raw_input("Enter string two:")

any([str1, str2]) and not all([str1, str2])

The first problem with this setup is that it most likely traverses the whole list twice and, at a minimum, will check at least one of the elements twice. So it may increase code comprehension, but it doesn’t lend to speed (which may differ negligibly depending on your use case).

The second problem with this setup is that it checks for exclusivity regardless of the number of variables. This is may at first be regarded as a feature, but the first problem becomes a lot more significant as the number of variables increases (if they ever do).


回答 19

Xor ^在Python中。它返回:

  • 整数的按位异或
  • 布尔逻辑异或
  • 集的独家联盟
  • 实现的类的用户定义结果__xor__
  • 未定义类型的TypeError,例如字符串或字典。

如果您打算在字符串上使用它们,则将它们强制转换可以bool使您的操作变得明确(您也可能表示set(str1) ^ set(str2))。

Xor is ^ in Python. It returns :

  • A bitwise xor for ints
  • Logical xor for bools
  • An exclusive union for sets
  • User-defined results for classes that implements __xor__.
  • TypeError for undefined types, such as strings or dictionaries.

If you intend to use them on strings anyway, casting them in bool makes your operation unambiguous (you could also mean set(str1) ^ set(str2)).


回答 20

XOR是在中实现的operator.xor

XOR is implemented in operator.xor.


回答 21

这就是我编写任何真值表的方式。特别是对于xor,我们有:

| a | b  | xor   |             |
|---|----|-------|-------------|
| T | T  | F     |             |
| T | F  | T     | a and not b |
| F | T  | T     | not a and b |
| F | F  | F     |             |

只需查看答案列中的T值,然后将所有真实情况与逻辑或连接在一起即可。因此,可以在情况2或3中生成此真值表。因此,

xor = lambda a, b: (a and not b) or (not a and b)

This is how I would code up any truth table. For xor in particular we have:

| a | b  | xor   |             |
|---|----|-------|-------------|
| T | T  | F     |             |
| T | F  | T     | a and not b |
| F | T  | T     | not a and b |
| F | F  | F     |             |

Just look at the T values in the answer column and string together all true cases with logical or. So, this truth table may be produced in case 2 or 3. Hence,

xor = lambda a, b: (a and not b) or (not a and b)

回答 22

我们可以通过使用以下命令轻松找到两个变量的异或:

def xor(a,b):
    return a !=b

例:

xor(真,假)>>>真

We can easily find xor of two variables by the using:

def xor(a,b):
    return a !=b

Example:

xor(True,False) >>> True