gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 21:09:14 26 4
gpt4 key购买 nike

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

if elt is the last element:
do statement

我如何实现这一目标

最佳答案

您可以通过使用 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
>>>

关于Python如何检查迭代器工具链中是否已到达最后一个元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2058894/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com