Python 为列表的长度生成重复索引

Python 为列表的长度生成重复索引,python,Python,我知道我可以做到以下几点: files = ['a', 'b', 'c', 'd', 'e', 'f'] for ind, file in enumerate(files): print(ind, file) (0, 'a') (1, 'b') (2, 'c') (3, 'd') (4, 'e') (5, 'f') 我想生成第二个索引,该索引在列表长度上重复0到n-1。例如,如果n=2print(ind,file,ind2) (0, 'a', 0) (1, 'b', 1) (2,

我知道我可以做到以下几点:

files = ['a', 'b', 'c', 'd', 'e', 'f']

for ind, file in enumerate(files):
    print(ind, file)

(0, 'a')
(1, 'b')
(2, 'c')
(3, 'd')
(4, 'e')
(5, 'f')
我想生成第二个索引,该索引在列表长度上重复0到
n-1
。例如,如果
n=2
print(ind,file,ind2)

(0, 'a', 0)
(1, 'b', 1)
(2, 'c', 0)
(3, 'd', 1)
(4, 'e', 0)
(5, 'f', 1)
如果
n=3

(0, 'a', 0)
(1, 'b', 1)
(2, 'c', 2)
(3, 'd', 0)
(4, 'e', 1)
(5, 'f', 2)

您可以结合使用
itertools.cycle
zip

from itertools import cycle
files = ['a', 'b', 'c', 'd', 'e', 'f']
n = 3
print(list(zip(range(len(files)), files, cycle(range(n)))))
这将产生:

[(0, 'a', 0), (1, 'b', 1), (2, 'c', 2), (3, 'd', 0), (4, 'e', 1), (5, 'f', 2)]

您可以结合使用
itertools.cycle
zip

from itertools import cycle
files = ['a', 'b', 'c', 'd', 'e', 'f']
n = 3
print(list(zip(range(len(files)), files, cycle(range(n)))))
这将产生:

[(0, 'a', 0), (1, 'b', 1), (2, 'c', 2), (3, 'd', 0), (4, 'e', 1), (5, 'f', 2)]

这对于模运算符来说是微不足道的:

for ind, file in enumerate(files):
    print(ind, file, ind % 3)

这对于模运算符来说是微不足道的:

for ind, file in enumerate(files):
    print(ind, file, ind % 3)

错误
打印(索引,文件,索引%3)
ugh。。。嗯。是的,这正是我想要的打印(ind,file,ind%3)ugh。。。嗯。是的,这正是我想要的,在这里完全是过度的…但在OP有一个不那么琐碎的问题时,也绝对值得为未来学习。在这里绝对是过度的…但在OP有一个不那么琐碎的问题时,也绝对值得为未来学习。