最简洁的方式来检查列表是否为空或仅包含无?
问题描述:
最简洁的方式来检查列表是否为空或仅包含无?最简洁的方式来检查列表是否为空或仅包含无?
我知道我可以测试:
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