我有3个这样的列表:
reel1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
reel2 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
reel3 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
我需要一个生成器函数,可以按顺序给我这些:
首先输出:
[
[1,2,3]
[1,2,3]
[1,2,3]
]
第二次输出:
[
[1,2,3]
[1,2,3]
[2,3,4] # Sequentially go through the list
]
...
第9次输出:
[
[1,2,3]
[2,3,4] # Next block of 3 of the second list
[1,2,3]
]
一直到:
[
[8,9,10] # Last block of 3 of the first list
[8,9,10] # Last block of 3 of the second list
[8,9,10] # Last block of 3 of the third list
]
实现上述目标的有效算法是什么?
我目前的方法:我正在使用3 for 循环来顺序浏览所有3个列表,但我不认为它有效。另外,如果我有超过3个列表,我将不得不缩进。
感谢您的帮助!
答案 0 :(得分:4)
>>> from itertools import product
>>> reel = list(range(1, 11))
>>> for i in product(zip(reel, reel[1:], reel[2:]), repeat=3):
... print(i)
要处理评论中提到的回绕,您可以使用
>>> for i in product(zip(*(reel[j:]+reel[:j] for j in range(3))), repeat=3):
... print(i)
答案 1 :(得分:1)
for i in itertools.product([[1,2,3,4,5,6,7,8,9,10][i:i+3] for i in range(0,8)], repeat=3):
print(i)