最簡潔的方式來檢查列表是否爲空或僅包含無?最簡潔的方式來檢查列表是否爲空或僅包含無?
我知道我可以測試:
if MyList:
pass
和:
if not MyList:
pass
但如果該列表中有一個項目(或多個項目),但是這些項目/ s爲無:
MyList = [None, None, None]
if ???:
pass
最簡潔的方式來檢查列表是否爲空或僅包含無?最簡潔的方式來檢查列表是否爲空或僅包含無?
我知道我可以測試:
if MyList:
pass
和:
if not MyList:
pass
但如果該列表中有一個項目(或多個項目),但是這些項目/ s爲無:
MyList = [None, None, None]
if ???:
pass
如果您關注列表中評估爲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)
。
可以使用all()
功能測試是所有元素都是無:
a = []
b = [None, None, None]
all(e is None for e in a) # True
all(e is None for e in b) # True
你可以直接與==
比較列表:
if x == [None,None,None]:
if x == [1,2,3]
它應該是'e is None'。 – nikow 2009-08-13 10:01:04
這可能更有效率,是的,但使用'=='不是*錯誤*。 – Stephan202 2009-08-13 10:17:25
小記:所有的鏈接實際上是任何... – 2009-08-13 11:11:22