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()渡された iterable のすべてFalseの要素が である場合にのみを返します。したがって、すべての要素が 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

Python の for ループが不要なため、入れ子にanyするitertools.chainよりも高速です。any

他のいくつかの選択肢は次のとおりです。

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 に答える