python 使用 any() 和 all() 检查列表是否包含一组值或另一组值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19211828/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 13:09:23  来源:igfitidea点击:

python using any() and all() to check if a list contains one set of values or another

pythonlist

提问by DasSnipez

My code is for a Tic Tac Toe game and checking for a draw state but I think this question could be more useful in a general sense.

我的代码用于 Tic Tac Toe 游戏并检查平局状态,但我认为这个问题在一般意义上可能更有用。

I have a list that represents the board, it looks like this:

我有一个代表董事会的列表,它看起来像这样:

board = [1,2,3,4,5,6,7,8,9]

When a player makes a move the int they moved on is replaced with their marker ('x' or 'o'), I already have checks in place to look for a winning state, what I can't do is check for a draw state, where none of the list values are ints but a winning state has not been set.

当玩家移动时,他们移动的 int 被替换为他们的标记('x' 或 'o'),我已经进行了检查以寻找获胜状态,我不能做的是检查平局状态,其中所有列表值都不是整数,但尚未设置获胜状态。

The code I have so far:

我到目前为止的代码:

if any(board) != playerOne or any(board) != playerTwo:
    print 'continue'
elif all(board) == playerOne or playerTwo:
    print 'Draw'

The if statement works, the elif does not, I think the problem is my 'or' operator, what I want to check for is: if the every item on the board is either playerOne marker or playerTwo marker, if I where to make the code:

if 语句有效,elif 无效,我认为问题在于我的“或”运算符,我要检查的是:如果板上的每个项目都是 playerOne 标记或 playerTwo 标记,如果我在哪里制作代码:

elif all(board) == playerOne or all(board) == playerTwo:

I would be checking to see if every place on the board was playerOne or every place on the board is playerTwo, which it won't be.

我会检查棋盘上的每个位置是否都是 playerOne 或棋盘上的每个位置都是 playerTwo,但事实并非如此。

So how do I check if the board is taken up by a combination of playerOne markers and playerTwo markers?

那么如何检查棋盘是否被 playerOne 标记和 playerTwo 标记的组合占用呢?

采纳答案by Erik Kaplun

Generally speaking:

通常来说,一般来说:

alland anyare functions that take some iterable and return True, if

all并且any是需要一些迭代和返回的函数True,如果

  • in the case of all(), no values in the iterable are falsy;
  • in the case of any(), at least one value is truthy.
  • 在 的情况下all(),迭代中没有值是假的;
  • 在 的情况下any(),至少有一个值为真。

A value xis falsy iff bool(x) == False. A value xis truthy iff bool(x) == True.

一个值x是假的 iff bool(x) == False。一个值x是真的 iff bool(x) == True

Any non-booleans in the iterable will be fine — bool(x)will coerce any xaccording to these rules: 0, 0.0, None, [], (), [], set(), and other empty collections will yield False, anything else True. The docstring for booluses the terms 'true'/'false' for 'truthy'/'falsy', and True/Falsefor the concrete boolean values.

可迭代中的任何非布尔值都可以 -bool(x)x根据以下规则强制任何:0, 0.0, None, [], (), [], set(), 和其他空集合将 yield False, any else True。的文档字符串bool使用术语 'true'/'false' 表示 'truthy'/'falsy',和True/False表示具体的布尔值。



In your specific code samples:

在您的特定代码示例中:

You misunderstood a little bit how these functions work. Hence, the following does something completely not what you thought:

您对这些功能的工作方式有一点误解。因此,以下内容完全不是您所想的:

if any(foobars) == big_foobar:

...because any(foobars)would first be evaluated to either Trueor False, and then that boolean value would be compared to big_foobar, which generally always gives you False(unless big_foobarcoincidentally happened to be the same boolean value).

...因为any(foobars)将首先评估为Trueor False,然后将该布尔值与 进行比较big_foobar,这通常总是给你False(除非big_foobar巧合的是相同的布尔值)。

Note:the iterable can be a list, but it can also be a generator/generator expression (≈ lazily evaluated/generated list) or any other iterator.

注意:iterable 可以是一个列表,但它也可以是一个生成器/生成器表达式(≈ 延迟计算/生成的列表)或任何其他迭代器。

What you want instead is:

你想要的是:

if any(x == big_foobar for x in foobars):

which basically first constructs an iterable that yields a sequence of booleans—for each item in foobars, it compares the item to big_foobarand emits the resulting boolean into the resulting sequence:

它基本上首先构造一个可迭代的,它产生一系列布尔值——对于 中的每个项目foobars,它将项目big_foobar与进行比较并将结果布尔值发送到结果序列中:

tmp = (x == big_foobar for x in foobars)

then anywalks over all items in tmpand returns Trueas soon as it finds the first truthy element. It's as if you did the following:

然后any遍历所有项目tmpTrue在找到第一个真实元素后立即返回。就好像您执行了以下操作:

In [1]: foobars = ['big', 'small', 'medium', 'nice', 'ugly']                                        

In [2]: big_foobar = 'big'                                                                          

In [3]: any(['big' == big_foobar, 'small' == big_foobar, 'medium' == big_foobar, 'nice' == big_foobar, 'ugly' == big_foobar])        
Out[3]: True

Note:As DSM pointed out, any(x == y for x in xs)is equivalent to y in xsbut the latter is more readable, quicker to write and runs faster.

注意:正如 DSM 所指出的,any(x == y for x in xs)相当于y in xs但后者更具可读性,编写速度更快,运行速度更快。

Some examples:

一些例子:

In [1]: any(x > 5 for x in range(4))
Out[1]: False

In [2]: all(isinstance(x, int) for x in range(10))
Out[2]: True

In [3]: any(x == 'Erik' for x in ['Erik', 'John', 'Jane', 'Jim'])
Out[3]: True

In [4]: all([True, True, True, False, True])
Out[4]: False

See also: http://docs.python.org/2/library/functions.html#all

另见:http: //docs.python.org/2/library/functions.html#all