假设我有两个列表
test1 = ["1","2","3"]
test2 = ["a","b","c","d","e"]
现在我想循环遍历它们。但是如果test2的长度大于test1
我找到了zip函数
for x , y in zip(test1,test2):
print(x)
print(y)
然而,当test1的所有元素都通过
迭代之后,这个函数将停止。
的示例输出1 a 2 b 3 c
我想要得到的是下面的
1 a 2 b 3 c 1 d 2 e
谢谢你的帮助!
使用itertools.cycle()
来重复第一个列表。
import itertools
for x, y in zip(itertools.cycle(test1), test2):
如果不需要包含zip(),则可以这样做:
test1 = [1,2,3]
test2 = ["a","b","c","d","e"]
mi, ma = min(test1,test2,key=len),max(test1,test2,key=len) #sort the lists by lenght
for i,x in enumerate(ma):
print(x,mi[i % len(mi)])
这将把最长列表中某项的索引除以最短列表的长度,得到最短列表中模的索引处的项。
您可以使用的模运算符(%
)来计算指数列表1:
test1 = ["1","2","3"]
test2 = ["a","b","c","d","e"]
for index, item in enumerate(test2):
# Print the item from list 1.
index_of_test1 = (index % len(test1))
print(test1[index_of_test1])
# Print the item from list 2.
print(item)