带有列表的Itertools计数

问题描述 投票:0回答:1

我想将itertools.count元素作为列表索引传递,但是会导致此错误:

TypeError:列表索引必须是整数或切片,而不是itertools.count

尝试int(counter)也不起作用,导致

TypeError:int()参数必须是字符串,类似字节的对象或数字,而不是'itertools.count'

from itertools import count

index = count()
l = [5,6,7,8,9,0]

while True:
    print(l[int(index)])

如何将计数作为列表索引传递?

python python-3.x loops itertools
1个回答
1
投票

您可以使用next从计数器中获取下一个元素。

from itertools import count

index = count()
l = [5, 6, 7, 8, 9, 0]

while True:
    print(l[next(index)])

但是您的循环的当前结构方式,当计数器达到6时最终会导致IndexError,因为您的列表只有6个元素。

输出将如下所示:

5
6
7
8
9
0
Traceback (most recent call last):
  File "test.py", line 7, in <module>
    print(l[next(index)])
IndexError: list index out of range

如果只想打印列表中的元素,则可以使用Python这样简单得多:

for element in l:
    print(element)
© www.soinside.com 2019 - 2024. All rights reserved.