Python如何检查迭代器工具链中是否已到达最后一个元素?

时间:2010-01-13 17:36:52

标签: python

for elt in itertools.chain.from_iterable(node):

if elt is the last element:
  do statement

我如何实现这个

4 个答案:

答案 0 :(得分:18)

您可以通过使用iter.next()在while循环中手动推进迭代器,然后捕获StopIteration异常来执行此操作:

>>> from itertools import chain
>>> it = chain([1,2,3],[4,5,6],[7,8,9])
>>> while True:
...     try:
...         elem = it.next()
...     except StopIteration:
...         print "Last element was:", elem, "... do something special now"
...         break
...     print "Got element:", elem
...     
... 
Got element: 1
Got element: 2
Got element: 3
Got element: 4
Got element: 5
Got element: 6
Got element: 7
Got element: 8
Got element: 9
Last element was: 9 ... do something special now
>>> 

答案 1 :(得分:10)

当循环结束时,elt变量不会超出范围,并且仍然保持循环给它的最后一个值。因此,您可以将代码放在循环的末尾,并对elt变量进行操作。它并不是非常漂亮,但是Python的范围规则也不是很好。

这个唯一的问题(谢谢,cvondrick)是循环可能永远不会执行,这意味着elt不存在 - 我们得到NameError。所以完整的方法大致是:

del elt # not necessary if we haven't use elt before, but just in case
for elt in itertools.chain.from_iterable(node):
    do_stuff_to_each(elt)
try:
    do_stuff_to_last(elt)
except NameError: # no last elt to do stuff to
    pass

答案 2 :(得分:2)

你本身不能。您需要存储当前项,推进迭代器,并捕获StopIteration异常。然后你需要以某种方式表明你有最后一项。

答案 3 :(得分:1)

我这样做:

rng = len(mlist)
for i in range(rng):
    foo = mlist[i]
    foo.do_something_for_every_item_regardless()
    if i == rng - 1: #since we go from 0 to rng-1
        foo.last_item_only_operation()