迭代堆栈(反向列表),是否有 isempty() 方法?
在 Python 中迭代堆栈的最佳方法是什么?
a = [1,2,3,4]
while (len(a) > 0)
print a.pop()
# prints 4, 3, 2, 1 in sequence
我找不到 isempty 方法,并且每次检查长度似乎都是错误的。
What's the best way to iterate over a stack in Python?
a = [1,2,3,4]
while (len(a) > 0)
print a.pop()
# prints 4, 3, 2, 1 in sequence
I couldn't find an isempty
method, and checking the length each time seems wrong somehow.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
容器的通常约定是,非空时它们为 True,空时为 False,因此您可以执行以下操作:
The usual convention for containers is that they are True while not empty and False when empty, so you can just do:
使用列表作为布尔条件,仅当列表为空时,其计算结果为
False
:这不仅更简洁,而且效率更高(对于 10,000 个列表,为 1.49 毫秒 vs 1.9 毫秒)它只需要检查是否有第一个元素:
您还可以使用
reversed( )
来获取反向迭代器:或者在一行中:
请注意,这不会从列表中删除元素。如有必要,您可以使用
del a[:]
来实现。Use the list as a boolean condition which evaluates to
False
only if the list is empty:Not only is this more concise, it is also more efficient (1.49ms vs 1.9ms for a list of 10,000) since it only has to check if there is a first element:
You can also use
reversed()
to get a reverse iterator:Or in one line:
Note that this will not remove the elements from the list. If necessary, you can achieve that with
del a[:]
.Python:什么是最好的检查列表是否为空的方法?
Stack (Python)
Python: What is the best way to check if a list is empty?
Stack (Python)