我想将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)])
如何将计数作为列表索引传递?
您可以使用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)