假设我有 2 个列表
test1 = ["1","2","3"]
test2 = ["a","b","c","d","e"]
现在我想遍历它们。但是如果 test2 的长度大于 test1
,则 test1 具有重复自身的能力我找到了压缩功能
for x , y in zip(test1,test2):
print(x)
print(y)
但是这个函数会在 test1 的所有元素都被迭代过后停止
样本输出
1 a 2 b 3 c
id喜欢得到的是以下
1 a 2 b 3 c 1 d 2 e
感谢您的帮助!
使用
itertools.cycle()
继续重复第一个列表。
import itertools
for x, y in zip(itertools.cycle(test1), test2):
您可以重复第一个列表足够多次,以至少匹配第二个列表的长度与
*
运算符。
for x, y in zip(test1 * (len(test2) // len(test1) + 1), 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)