不使用“not”命令检查list是否为空

2024-04-19 03:34:57 发布

您现在位置:Python中文网/ 问答频道 /正文

如果不使用not命令,我如何确定列表是否为空?
我试过的是:

if list3[0] == []:  
    print "No matches found"  
else:  
    print list3

我是个初学者,如果我犯了愚蠢的错误,请原谅。


Tags: no命令列表if错误notelseprint
3条回答

你可以通过测试列表的“真实性”来发现列表是否为空:

>>> bool([])
False
>>> bool([0])     
True

而在第二种情况下,0是False,但是列表[0]是True,因为它包含一些内容。(如果您想测试一个包含所有错误内容的列表,如果li中的任何项是真的,则使用allanyany(e for e in 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...

根据PEP 8,这是正确的方法:

• 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)

使用try测试列表是否存在特定索引:

>>> try:
...    li[3]=6
... except IndexError:
...    print 'no bueno'
... 
no bueno

因此,您可能需要将代码的顺序颠倒为:

if list3:  
    print list3  
else:  
    print "No matches found"

按优先顺序:

# 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

检查它的长度。

l = []
print len(l) == 0

相关问题 更多 >