2024-04-19 03:34:57 发布
网友
如果不使用not命令,我如何确定列表是否为空? 我试过的是:
if list3[0] == []: print "No matches found" else: print list3
我是个初学者,如果我犯了愚蠢的错误,请原谅。
你可以通过测试列表的“真实性”来发现列表是否为空:
>>> bool([]) False >>> bool([0]) True
而在第二种情况下,0是False,但是列表[0]是True,因为它包含一些内容。(如果您想测试一个包含所有错误内容的列表,如果li中的任何项是真的,则使用all或any:any(e for e in li)为真。)
0
[0]
li
any(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)
• 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
>>> 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
你可以通过测试列表的“真实性”来发现列表是否为空:
而在第二种情况下,
0
是False,但是列表[0]
是True,因为它包含一些内容。(如果您想测试一个包含所有错误内容的列表,如果li
中的任何项是真的,则使用all或any:any(e for e in li)
为真。)这就产生了一个成语:
根据PEP 8,这是正确的方法:
使用
try
测试列表是否存在特定索引:因此,您可能需要将代码的顺序颠倒为:
按优先顺序:
如果您同时拥有If和else,则还可以重新订购案例:
检查它的长度。
相关问题 更多 >
编程相关推荐