python - python中所有可能的组合
问题描述
我正在寻找解决这个问题的所有可能的python组合:
list1 = ['M','W','D']
list2 = ['y','n']
我想要的是:
[[('M', 'y'), ('W', 'n'), ('D', 'n')], [('M', 'y'), ('D', 'n'), ('W', 'n'), ....
我需要像这样拥有 M、W、D 的所有可能性:
M W D
y n y
y y y
y y n
y n n
n y y
n n y
. . .
我试过了:
import itertools
list1 = ['M','W','D']
list2 = ['y','n']
all_combinations = []
list1_permutations = itertools.permutations(list1, len(list2))
for each_permutation in list1_permutations:
zipped = zip(each_permutation, list2)
all_combinations.append(list(zipped))
print(all_combinations)
我得到:
[[('M', 'y'), ('W', 'n')], [('M', 'y'), ('D', 'n')], [('W', 'y'), ('M', 'n')], [('W', 'y'), ('D', 'n')], [('D', 'y'), ('M', 'n')], [('D', 'y'), ('W', 'n')]]
这绝对不是我想要的,因为我需要将 list1 的所有元素显示到同一个列表中并与 list2 的元素组合。
我不确定列表是否适合这个问题,但我需要的是 'D'、'W'、'M' 和 'y'、'n' 的所有可能性
解决方案
您可以使用来生成长度为 的itertools.product
所有此类项目组合,然后使用每个组合压缩以进行输出:list2
list1
list1
[list(zip(list1, c)) for c in itertools.product(list2, repeat=len(list1))]
这将返回:
[[('M', 'y'), ('W', 'y'), ('D', 'y')],
[('M', 'y'), ('W', 'y'), ('D', 'n')],
[('M', 'y'), ('W', 'n'), ('D', 'y')],
[('M', 'y'), ('W', 'n'), ('D', 'n')],
[('M', 'n'), ('W', 'y'), ('D', 'y')],
[('M', 'n'), ('W', 'y'), ('D', 'n')],
[('M', 'n'), ('W', 'n'), ('D', 'y')],
[('M', 'n'), ('W', 'n'), ('D', 'n')]]
推荐阅读
- visual-studio - Visual Studio 不接受 Xamarin UWP 应用的 makecert 证书
- excel - 针对 IBM DB2 运行带有嵌套子查询和联合的 Excel VBA 查询
- javascript - 我应该如何在 JavaScript 中“屈服”?
- sql - 根据组排除列表查询逻辑以获得预期结果
- repository - Stash 和 Bitbucket 是什么关系?
- python - 如何使用 jq 获取我的 json 的所有第一个对象?
- caching - ServiceStack 是否缓存内部请求?
- android - 在 PlayStore 中私有分发 Android 应用程序
- php - PHP/Laravel - 管理员能够查看用户表并编辑信息
- laravel - Laravel Nova - 资源页面的 Point Nova 路径