Sve*_*ach 93
如果d
是你的双端队员,请使用
if d:
# not empty
else:
# empty
Run Code Online (Sandbox Code Playgroud)
这将隐式转换d
为a bool
,True
如果deque包含任何项目并且False
它是空的,则会产生.
Ray*_*ger 10
主要有两种方式:
容器可以用作布尔值(与 False
指示容器为空):
Python 中的容器也有一种__len__()
指示其大小的方法。
这里有一些模式:
non_empty = bool(d) # Coerce to a boolean value
empty = not d # Invert the boolean value
if d: # Test the boolean value
print('non-empty')
while d: # Loop until empty
x = d.pop()
process(x)
if len(d) == 0: # Test the size directly
print('empty')
Run Code Online (Sandbox Code Playgroud)
后一种技术不像其他技术那样快速或简洁,但对于可能不知道容器的布尔值的读者来说,它确实具有明确的优点。
其他方式也是可能的。例如,索引 with为空序列d[0]
引发IndexError
。我已经看到这个使用了几次。
归档时间: |
|
查看次数: |
31059 次 |
最近记录: |