2009-08-13 69 views

回答

15

的一種方法是使用all和列表理解:

if all(e is None for e in myList): 
    print('all empty or None') 

這適用於空列表爲好。更一般地,以測試列表是否只包含的東西,計算結果爲False,您可以使用any

if not any(myList): 
    print('all empty or evaluating to False') 
+2

它應該是'e is None'。 – nikow 2009-08-13 10:01:04

+0

這可能更有效率,是的,但使用'=='不是*錯誤*。 – Stephan202 2009-08-13 10:17:25

+0

小記:所有的鏈接實際上是任何... – 2009-08-13 11:11:22

2

如果您關注列表中評估爲true的元素:

if mylist and filter(None, mylist): 
    print "List is not empty and contains some true values" 
else: 
    print "Either list is empty, or it contains no true values" 

如果要嚴格檢查None,在if上述聲明使用filter(lambda x: x is not None, mylist)代替filter(None, mylist)

9

可以使用all()功能測試是所有元​​素都是無:

a = [] 
b = [None, None, None] 
all(e is None for e in a) # True 
all(e is None for e in b) # True 
4

你可以直接與==比較列表:

if x == [None,None,None]: 

if x == [1,2,3] 
相關問題