python使用any()和all()检查列表是否包含一组值或另一组值 [英] python using any() and all() to check if a list contains one set of values or another

查看:59
本文介绍了python使用any()和all()检查列表是否包含一组值或另一组值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的代码用于井字游戏,并检查平局状态,但我认为从一般意义上讲,这个问题可能更有用.

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.

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

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

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

当玩家移动时,他们继续前进的int被标记("x"或"o")所取代,我已经准备好了寻找获胜状态的检查,我不能做的就是检查对于平局状态,列表值都不是整数,但是尚未设置获胜状态.

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.

我到目前为止的代码:

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

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

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:

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

我要检查棋盘上的每个位置是否都是playerOne,或者棋盘上的每个位置都是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?

推荐答案

通常来说:

allany是需要一些迭代并返回True的函数,如果

all and any are functions that take some iterable and return True, if

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

x是伪造的,如果bool(x) == False. 值xbool(x) == True是对的.

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

任何可迭代的非布尔值都很好-bool(x)将根据以下规则强制执行任何x:00.0None[]()set()和其他空集合将产生False,而其他任何内容都将产生True. bool的文档字符串使用术语"true"/"false"表示"truthy"/"falsy",并使用True/False表示具体的布尔值.

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

在您的特定代码示例中:

您误解了这些功能的工作原理.因此,以下操作完全无法实现您的预​​期:

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

if any(foobars) == big_foobar:

...因为因为any(foobars)首先将被评估为TrueFalse,然后将该布尔值与big_foobar进行比较,所以通常会始终为您提供False(除非big_foobar碰巧是相同的布尔值).

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

注意:可迭代项可以是列表,但也可以是生成器/生成器表达式(≈延迟求值/生成的列表)或任何其他迭代器.

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

您想要的是:

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

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

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

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

然后any遍历tmp中的所有项目,并在找到第一个真实元素后立即返回True.就像您执行以下操作一样:

then any walks over all items in tmp and returns True as soon as it finds the first truthy element. It's as if you did the following:

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

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

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

一些示例:

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

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

这篇关于python使用any()和all()检查列表是否包含一组值或另一组值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆