简体   繁体   English

从多个具有重复列表的列表中生成所有组合

[英]Generate all combinations from multiple lists with repeat lists

I have multiple lists, some of them are repeats and I need all combinations, excluding ones where the same element from a repeated list is chosen. 我有多个列表,其中一些是重复列表,我需要所有组合,但从重复列表中选择相同元素的列表除外。 For example, I have 例如,我有

import itertools
list1 = [1,2,3]
list2 = [4,5,6]
list3 = [4,5,6]
list4 = [7,8,9]
a = [list1,list2,list3,list4]
print list(itertools.product(*a))

which outputs 哪个输出

(1,4,4,7)
(1,4,4,8)
(1,4,4,9)
(1,4,5,7)
.
.
.

etc, as you'd expect, but what I want it to do is output every combination, without repeating elements from lists 2 and 3. Like this: 等等,正如您所期望的那样,但我要执行的是输出每个组合,而无需重复列表2和3中的元素。

(1,4,5,7)
(1,4,5,8)
(1,4,5,9)
(1,4,6,7)
(1,4,6,8)
(1,4,6,9)
(1,5,6,7)
(1,5,6,8)
(1,5,6,9)
(2,4,5,7)
.
.
.

I'd obviously like to avoid having to remove them manually after creating the list, but any help on how to do this efficiently is really appreciated. 我显然希望避免在创建列表后必须手动删除它们,但是对如何有效地执行此操作的任何帮助都非常感谢。 Thanks. 谢谢。

The easy way is a generator expression with a filter: 简单的方法是带有过滤器的生成器表达式:

print list(item for item in itertools.product(*a) if item[1] != item[2])

If two items are considered the same if they contain the same elements, and if each item is guaranteed to contain no repeated elements, you can discard duplicates by changing them into set s and only adding them to your list if they're not already in it: 如果两个项目包含相同的元素,则认为它们是相同的;并且如果每个项目都保证不包含重复的元素,则可以通过将重复项更改为set并仅将其添加到list来将其删除,从而丢弃重复项它:

result = []
for item in itertools.product(*a):
    if item[1]==item[2]:
        continue
    item = set(item)
    if item not in result:
        result.append(item)

print result

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

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