Python How to I check if last element has been reached in iterator tool chain?

后端 未结 4 448
臣服心动
臣服心动 2021-01-31 20:29
for elt in itertools.chain.from_iterable(node):

if elt is the last element:
  do statement

How do I achieve this

4条回答
  •  一个人的身影
    2021-01-31 20:59

    You can do this by manually advancing the iterator in a while loop using iter.next(), then catching the StopIteration exception:

    >>> 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
    >>> 
    

提交回复
热议问题