Python算法顺序生成slot machin的所有可能结果

2024-04-19 20:10:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我有三张这样的单子:

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]

我需要一个生成器函数,它可以依次给出:

第一次输出:

^{pr2}$

第二次输出:

[
    [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个以上的列表,我将不得不缩进很多。在

谢谢你的帮助!在


Tags: ofthe方法函数goblocklist单子
2条回答
>>> from itertools import product
>>> reel = list(range(1, 11))
>>> for i in product(zip(reel, reel[1:], reel[2:]), repeat=3):
...     print(i)

要处理注释中提到的包装,可以使用

^{pr2}$
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)

相关问题 更多 >