Python 不使用'not'命令检查列表是否为空
如果不使用not命令,如何确定列表是否为空?Python 不使用'not'命令检查列表是否为空,python,list,is-empty,Python,List,Is Empty,如果不使用not命令,如何确定列表是否为空? 以下是我尝试过的: if list3[0] == []: print("No matches found") else: print(list3) 我是一个初学者,如果我犯了愚蠢的错误,请原谅。检查它的长度 l = [] print len(l) == 0 按优先顺序: # Good if not list3: # Okay if len(list3) == 0: # Ugly if list3 == []: #
以下是我尝试过的:
if list3[0] == []:
print("No matches found")
else:
print(list3)
我是一个初学者,如果我犯了愚蠢的错误,请原谅。检查它的长度
l = []
print len(l) == 0
按优先顺序:
# Good
if not list3:
# Okay
if len(list3) == 0:
# Ugly
if list3 == []:
# Silly
try:
next(iter(list3))
# list has elements
except StopIteration:
# list is empty
如果您同时拥有If和else,您还可以重新订购案例:
if list3:
# list has elements
else:
# list is empty
您可以通过测试列表的“真实性”来确定列表是否为空:
>>> bool([])
False
>>> bool([0])
True
在第二种情况下,0
为False,但是列表[0]
为True,因为它包含一些内容。(如果要测试列表是否包含所有虚假内容,请使用或:any(li中的e代表e)
如果li
中的任何项目为真,则为真。)
这就产生了这样一个习语:
if li:
# li has something in it
else:
# optional else -- li does not have something
if not li:
# react to li being empty
# optional else...
根据我的观点,这是正确的方法:
•对于序列(字符串、列表、元组),使用空序列为假的事实
Yes: if not seq:
if seq:
No: if len(seq)
if not len(seq)
您可以使用try
测试列表是否存在特定索引:
>>> try:
... li[3]=6
... except IndexError:
... print 'no bueno'
...
no bueno
因此,您可能希望将代码的顺序颠倒为:
if list3:
print list3
else:
print "No matches found"
你会这样做的
if len(list3) == 0:
print("No matches found")
Python提供了一个内置的any()函数来检查iterable是否为空:
>>>list=[]
>>>any(list)
False
如果iterable包含“True”值,则函数返回True,否则返回False
但是,请注意,列表[0]在any()中也返回False。not有什么问题?这是学校的任务,我现在不应该知道。我之所以知道这一点,是因为我以前搜索过答案。顶部提示可能重复:
not
是运算符,而不是命令实际上,在布尔上下文中,空列表是False
。无需明确测试len()
。需要注意的是,在引擎盖下,1
和2
在大多数情况下都在做相同的事情。@sr2222抱歉。由于Python2.x中的语法错误,删除了注释。但是,如果在Python 3.x中打印list3 else(“未找到匹配项”),则可以执行无操作。@Aya您也可以执行尝试:iter(l).next()
除了StopIteration:#执行stuff
。当然,“可以”和“应该”是不同的东西。。。编辑:噢,约翰比我先做到了。。。虽然尝试:l[0]
但索引器除外:#dostuff
同样愚蠢…@sr2222确实如此。不过看看人们能想出多少疯狂的方法会很有趣<代码>列表3或打印(“未找到匹配项”)
也可能会起作用。;-)