首页 > 解决方案 > 从python中的多个列表生成所有组合

问题描述

我有一个数据集,其中包含多个列表,每个列表具有不同数量的元素。例如。

list1 = ['a','b','c']

list2 = ['d','e']

list3 = ['f','g','h','i']

我想从这些列表中生成所有可能的唯一组合,条件如下:

  1. 一个组合中的元素数量应为 5
  2. 每个列表中至少有 1 个元素。

我该怎么做呢?

标签: pythonpandascombinationspermutation

解决方案


我认为这会做到(其中很多步骤可以组合,但保留它们以显示步骤)

创建一个包含所有项目的新列表

list4 = list1 + list2 + list3

还有另一个列表来遍历它们以找到所有 5 种组合(您没有指定订单或更换,因此请在此处阅读并根据需要进行更改)

list5 = list(itertools.combinations(list4, 5))

然后从每个列表中删除没有元素的项目。

[i for i in list5 if any(j in list1 for j in i) and any(j in list2 for j in i) and any(j in list3 for j in i)]

所以在一行中它可能是:

[i for i in itertools.combinations(list1 + list2 + list3, 5) if any(j in list1 for j in i) and any(j in list2 for j in i) and any(j in list3 for j in i)]

推荐阅读