简体   繁体   English

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

[英]All combinations of a list of all lists iterating through a for loop

I am working on a program and I am having a bit of difficulty trying to figure about to make the for loop do what I would like.我正在开发一个程序,我在试图让 for 循环做我想做的事情时遇到了一些困难。

As of right now, the for statement goes through every single combination of all lists and makes 5 choices, that is right, I want 5 choices.截至目前,for 语句遍历所有列表的每一个组合并做出 5 个选择,没错,我想要 5 个选择。

However, it creates a lot of overlap, since I am adding all the lists together and picking 5 items.但是,它会产生很多重叠,因为我将所有列表添加在一起并选择 5 个项目。 I do get what I want, but along with many combinations I do not, since all I am doing is adding all 5 lists together, I want them to be picked independently.我确实得到了我想要的东西,但是我没有得到许多组合,因为我所做的只是将所有 5 个列表加在一起,我希望它们被独立挑选。

I would like the for statement to only go through each list row by row, and pick all combinations, with no overlap.我希望 for 语句仅通过每个列表逐行显示 go,并选择所有组合,没有重叠。

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()

The output I want is something like this, pull each item out from each list, one at a time:我想要的 output 是这样的,从每个列表中拉出每个项目,一次一个:

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]
...

Let me know if you have any questions, this is difficult to explain, I know.如果您有任何问题,请告诉我,这很难解释,我知道。

Since its a iterator, you can use next :由于它是一个迭代器,您可以使用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)

And so on.等等。

You can have this next in your function which will yield one combination at a time.你可以在你的next中使用这个,它一次会产生一个组合。

This cartesian product shall do it in the order you want:此笛卡尔积应按您想要的顺序执行:

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)

The cartesian product has no duplicates unless your input lists do, if it's the case maybe think of using set() .笛卡尔积没有重复项,除非您的输入列表这样做,如果是这种情况,可能会考虑使用set()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM