[英]Python how to get all combinations of elements from groups with at most one element from each group and at least one element from one of the groups
I'm working in Python 3.我在 Python 3 工作。
I have five lists like the following:我有五个列表,如下所示:
l1 = [1, 2]
l2 = ['A', 'B', 'C']
l3 = ['d', 'e', 'f', 'g']
l4 = ['word1', 'word2', 'word3', 'word4', 'word5']
l5 = [10, 20, 30, 40, 50, 60]
The lists have variable lengths, and every element in every list is unique.列表具有可变长度,并且每个列表中的每个元素都是唯一的。 I want to find all possible combinations of elements in the lists that meet the following conditions:我想在满足以下条件的列表中找到所有可能的元素组合:
[]
is not a permitted combination.换句话说,空列表[]
不是允许的组合。[1, 'A', 'B'], ['d', 'e'], ['C', 'word2', 'word3']
.例如,这些列表中的每一个都不允许作为组合: [1, 'A', 'B'], ['d', 'e'], ['C', 'word2', 'word3']
。[1], [1, 'A'], [1, 'A', 'd'], [1, 'A', 'd', 'word1'], [1, 'A', 'd', 'word1', 10]
.例如,这些列表中的每一个都是允许的组合: [1], [1, 'A'], [1, 'A', 'd'], [1, 'A', 'd', 'word1'], [1, 'A', 'd', 'word1', 10]
。[1, 'A']
is the same combination as ['A', 1]
, and [1, 'B', 'word2']
is the same combination as ['B', 'word2', 1]
.例如, [1, 'A']
与['A', 1]
的组合相同,而[1, 'B', 'word2']
与['B', 'word2', 1]
组合相同['B', 'word2', 1]
.[1, 1, 'A'], ['A', 'd', 'A']
.例如,这些列表中的每一个都不允许作为组合: [1, 1, 'A'], ['A', 'd', 'A']
。A consequence of these conditions is that every combination will have at least one element and at most five elements.这些条件的结果是每个组合都至少有一个元素,最多有五个元素。
A solution like the one mentioned here won't work since it doesn't meet condition 3 above.像这里提到的那样的解决方案将不起作用,因为它不满足上述条件 3。
I'm looking for an elegant and efficient solution.我正在寻找一个优雅而有效的解决方案。 I'm also looking for a general solution since the actual lists I'm working with differ in size and content from the ones given above.我也在寻找一个通用的解决方案,因为我正在使用的实际列表的大小和内容与上面给出的列表不同。
Add a null element to each list to represent not including any element from that list:将 null 元素添加到每个列表以表示不包括该列表中的任何元素:
all_lists = [l + [None] for l in [l1, l2, l3, l4, l5]]
Now, it's a simple matter to cycle through all the permutations, removing the None
elements:现在,循环遍历所有排列,删除None
元素是一件简单的事情:
for cross in itertools.product(*all_lists):
combo = [item for item in cross if item is not None] # Remove "None" elements
if combo: # Ignore the empty list
print(combo)
Or, to collect them into a list, you can use (nested) comprehension:或者,要将它们收集到一个列表中,您可以使用(嵌套)理解:
result = [combo for combo in [
[item for item in cross if item is not None]
for cross in itertools.product(*all_lists)]
if combo]
You can try this你可以试试这个
l1 = [1, 2]
l2 = ['A', 'B', 'C']
l3 = ['d', 'e', 'f', 'g']
l4 = ['word1', 'word2', 'word3', 'word4', 'word5']
l5 = [10, 20, 30, 40, 50, 60]
import itertools as itt
result = []
for n in range(1, 5):
for ls in itt.combinations([l1, l2, l3, l4, l5], n):
result+= list(itt.product(*ls))
print(result)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.