如何检查列表是否为空?
时间:2020-03-05 18:50:33 来源:igfitidea点击:
例如,如果通过以下内容:
a = []
如何检查`a'是否为空?
解决方案
回答
if not a: print("List is empty")
使用空列表的隐式布尔值是非常Python的。
回答
我认为以下是首选:
if not a: print("The list is empty or null")
回答
空列表本身在真实值测试中被认为是错误的(请参阅python文档):
a = [] if a: print "not empty"
@达伦·托马斯(Daren Thomas)
EDIT: Another point against testing the empty list as False: What about polymorphism? You shouldn't depend on a list being a list. It should just quack like a duck - how are you going to get your duckCollection to quack ''False'' when it has no elements?
duckCollection应该实现__nonzero__
或者__len__
,因此if a:可以正常工作。
回答
我更喜欢以下内容:
if a == []: print "The list is empty."
可读性强,我们不必担心调用诸如len()之类的函数来遍历变量。尽管我不完全确定像这样的BigO表示法是什么...但是Python如此快速,我怀疑除非a
巨大,否则它是否重要。
回答
pythonic的方法来自PEP 8样式指南(其中Yes表示推荐,No表示不推荐):
For sequences, (strings, lists, tuples), use the fact that empty sequences are false. Yes: if not seq: if seq: No: if len(seq): if not len(seq):
回答
len()是Python列表,字符串,字典和集合的O(1)操作。 Python在内部跟踪这些容器中的元素数量。
JavaScript具有"真/假"的相似概念。