python - 从python中的多个列表生成所有组合
问题描述
我有一个数据集,其中包含多个列表,每个列表具有不同数量的元素。例如。
list1 = ['a','b','c']
list2 = ['d','e']
list3 = ['f','g','h','i']
我想从这些列表中生成所有可能的唯一组合,条件如下:
- 一个组合中的元素数量应为 5
- 每个列表中至少有 1 个元素。
我该怎么做呢?
解决方案
我认为这会做到(其中很多步骤可以组合,但保留它们以显示步骤)
创建一个包含所有项目的新列表
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)]
推荐阅读
- kotlin - 错误:Kotlin:类型推断在表达式时失败
- rest - URL中的@符号是什么意思?
- reactjs - 组件更新但状态不更新 redux 工具包
- c# - C#异步/等待外部事件处理程序触发
- asp.net-mvc - 如何在差异应用程序中跨会话但在同一域中?
- java - 如何将 RecyclerView 连接到类?
- java - Java JNI 错误请检查您的安装。苹果系统
- javascript - 在 nodejs 服务器中运行 php 脚本
- bash - inotifywait 一直在中止
- android - Cant Firebase 在单个 RecyclerView 中显示来自多个引用的数据