4

我有以下代码(元组列表):

x = [(None, None, None), (None, None, None), (None, None, None)]

我怎么知道这基本上评估为False

换句话说,我怎么能做这样的事情:

if not x: # x should evaluate to False
    # do something
4

2 回答 2

9

使用嵌套any()调用:

if not any(any(inner) for inner in x):

any()仅当传递给它的可迭代对象中的所有元素都是False时才返回。因此只有当所有元素都为假时:Falsenot any()True

>>> x = [(None, None, None), (None, None, None), (None, None, None)]
>>> not any(any(inner) for inner in x)
True
>>> x = [(None, None, None), (None, None, None), (None, None, 1)]
>>> not any(any(inner) for inner in x)
False
于 2013-07-09T18:23:10.387 回答
3

您可以使用anywith itertools.chain,它比嵌套更快,any因为不需要 python for-loop:

很少有其他选择是:

not any (chain.from_iterable(x))
not any (chain(*x))
not any(map(any,x))
not any(imap(any,x))   #itertools.imap

时间比较:

>>> from itertools import chain,imap
>>> x = [(None, None, None), (None, None, None), (None, None, None)]
>>> %timeit not any (chain.from_iterable(x))       #winner
100000 loops, best of 3: 1.08 us per loop
>>> %timeit not any (chain(*x))
1000000 loops, best of 3: 1.29 us per loop
>>> %timeit not any(any(inner) for inner in x)
100000 loops, best of 3: 1.76 us per loop
>>> %timeit not any(map(any,x))
100000 loops, best of 3: 1.5 us per loop
>>> %timeit not any(imap(any,x))
100000 loops, best of 3: 1.37 us per loop


>>> x = [(None, None, None), (None, None, None), (None, None, None)]*1000
>>> %timeit not any (chain.from_iterable(x))      #winner
1000 loops, best of 3: 462 us per loop
>>> %timeit not any (chain(*x))
1000 loops, best of 3: 537 us per loop
>>> %timeit not any(any(inner) for inner in x)
1000 loops, best of 3: 1.26 ms per loop
>>> %timeit not any(map(any,x))
1000 loops, best of 3: 672 us per loop
>>> %timeit not any(imap(any,x))
1000 loops, best of 3: 765 us per loop

>>> x = [(None, None, None), (None, None, None), (None, None, None)]*10**5
>>> %timeit not any (chain.from_iterable(x))       #winner
10 loops, best of 3: 50.1 ms per loop        
>>> %timeit not any (chain(*x))                  
10 loops, best of 3: 70.3 ms per loop
>>> %timeit not any(any(inner) for inner in x)
10 loops, best of 3: 127 ms per loop
>>> %timeit not any(map(any,x))
10 loops, best of 3: 76.2 ms per loop
>>> %timeit not any(imap(any,x))
1 loops, best of 3: 64.9 ms per loop
于 2013-07-09T18:43:14.573 回答