Iterating over a stack (reverse list), is there an isempty() method?
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.
通常的容器惯例是,它们是真的,而不是空的,空的时候是假的,所以你可以这样做:
while a:
print a.pop()
Use the list as a boolean condition which evaluates to False
only if the list is empty:
>>> while a:
... print a.pop()
...
4
3
2
1
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:
$ python -mtimeit -c 'a=range(10000)
while len(a):
a.pop()'
10000 loops, best of 3: 1.9 msec per loop
$ python -mtimeit -c 'a=range(10000)
while a:
a.pop()'
1000 loops, best of 3: 1.49 msec per loop
You can also use reversed()
to get a reverse iterator:
>>> for n in reversed(a):
... print n
...
4
3
2
1
Or in one line:
print 'n'.join(map(str, reversed(a)))
Note that this will not remove the elements from the list. If necessary, you can achieve that with del a[:]
.
Python: What is the best way to check if a list is empty?
Stack (Python)
链接地址: http://www.djcxy.com/p/22508.html上一篇: C#int来枚举转换