遍历for循环的所有列表列表的所有组合

2024-04-28 07:37:38 发布

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

我正在编写一个程序,我在尝试如何使for循环达到我想要的效果时遇到了一些困难

到目前为止,for语句遍历所有列表的每个组合,并做出5个选择,也就是说,我想要5个选择

但是,这会造成很多重叠,因为我将所有列表添加到一起,并选择5个项目。我确实得到了我想要的,但随着许多组合,我没有,因为我所做的是将所有5个列表添加到一起,我希望它们能够独立地被挑选出来

我希望for语句只逐行遍历每个列表,并选择所有组合,没有重叠

from itertools import combinations

.
.
.
.

def playerpick():
    P1 = [1,2,3,4,7]
    P2 = [1,8,13,14,17,29]
    P3 = [1,2,3]
    P4 = [1,7,8,12,15]
    P5 = [1,2,3,4]
    all_lists = P1 + P2 + P3 + P4 + P5
    for (a,b,c,d,e) in combinations(all_lists, 5):
        pick1 = a
        pick2 = b
        pick3 = c
        pick4 = d
        pick5 = e

playerpick()

我想要的输出是这样的,从每个列表中取出每个项目,一次一个:

output 1: [1,1,1,1,1]
output 2: [2,1,1,1,1]
output 3: [3,1,1,1,1]
output 4: [4,1,1,1,1]
output 5: [7,1,1,1,1]
output 6: [1,8,1,1,1](next combination)
output 7: [2,8,1,1,1]
output 8: [3,8,1,1,1]
output 9: [4,8,1,1,1]
output 10: [7,8,1,1,1]
output 11: [1,13,1,1,1](next combination)
output 12: [2,13,1,1,1]
...

如果您有任何问题,请告诉我,这很难解释,我知道


Tags: 项目列表foroutput语句alllistsnext
2条回答

因为它是迭代器,所以可以使用next

In [240]: x = itertools.product(*a)

In [241]: next(x)
Out[241]: (1, 4, 7)

In [242]: next(x)
Out[242]: (1, 4, 8)

等等

您可以在函数中使用这个next,它将一次生成一个组合

此笛卡尔积应按您想要的顺序进行:

import itertools
import pprint
 
def cartesian_product(lists):
    return list(itertools.product(*lists))

for list in [(P1,P2,P3,P4,P5)]:
        print(list, '=>')
        pprint(cartesian_product(list), indent=2)

笛卡尔积没有重复项,除非您的输入列表有重复项,如果是这种情况,可以考虑使用set()

相关问题 更多 >