简体   繁体   English

多个列表的组合

[英]Combinations of multiple lists

Suppose I have three lists: 假设我有三个列表:

list1 --> [a, b, c, d, e, f, g, h]
list2 --> [i, j, k]
list3 --> [l, m, n, o, p]

I wish to generate all combinations where I take five elements from list1, two elements from list2 and three elements from list3. 我希望生成所有组合,其中我从list1中获取五个元素,list2中的两个元素和list3中的三个元素。

eg. 例如。

a, b, c, d, e, i, j, l, m, n  
a, b, c, d, e, i, j, l, m, o
etc.

I tried to use itertools.combinations. 我试着使用itertools.combinations。

l1_combinations = itertools.combinations(list1, 5)
l2_combinations = itertools.combinations(list2, 2)
l3_combinations = itertools.combinations(list3, 3)
for l1_iterator in list(l1_combinations):
    for l2_iterator in list(l2_combinations): #added a missing )
        for l3_iterator in list(l3_combinations):
            sample = l1_iterator + l2_iterator + l3_iterator
            print(sample)

But I am getting output with iterations happening only on list3. 但我得到的输出迭代只发生在list3上。 In all the output, only first five elements from list1 and first two elements from list2 are present. 在所有输出中,仅存在list1中的前五个元素和list2中的前两个元素。 Combinations with other elements from those two lists aren't present. 与这两个列表中的其他元素的组合不存在。

Can someone help me here and also explain what exactly did i miss ? 有人可以帮助我,并解释我到底错过了什么?

As an alternative to regenerating the list of combinations, compute the product of the combinations up front; 作为重新生成组合列表的替代方法,请预先计算组合的乘积 ; this also saves you from nesting for loops. 这也可以避免嵌套for循环。

from itertools import combinations, product


list1 = list("abcdefgh")
list2 = list("ijk")
list3 = list("lmnop")

l1 = combinations(list1, 5)
l2 = combinations(list2, 2)
l3 = combinations(list3, 3)
for c1, c2, c3 in product(l1, l2, l3):
    sample = c1 + c2 + c3
    print(sample)

Don't iterate over the same iterator multiple times, after the first time it's exhausted. 在第一次耗尽之后,不要多次迭代同一个迭代器。 Iterate over a fresh iterator each time: 每次迭代一个新的迭代器:

for l1_iterator in itertools.combinations(list1, 5):
    for l2_iterator in itertools.combinations(list2, 2):
        for l3_iterator in itertools.combinations(list3, 3):
            sample = l1_iterator + l2_iterator + l3_iterator
            print(sample)

Or make lists of each one in advance to avoid recomputation: 或者提前列出每个列表以避免重新计算:

l1_combinations = list(itertools.combinations(list1, 5))
l2_combinations = list(itertools.combinations(list2, 2))
l3_combinations = list(itertools.combinations(list3, 3))
for l1_iterator in l1_combinations:
    for l2_iterator in l2_combinations:
        for l3_iterator in l3_combinations:
            sample = l1_iterator + l2_iterator + l3_iterator
            print(sample)

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

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