python - python中两个列表的排列而不使用python中的itertools组合或合并列表可能吗?
问题描述
在两个子列表的情况下
`[[A,B],[1,2]]`
我想要输出
[[A,B],[1,2]
[A,B],[2,1]
[B,A],[1,2]
[B,A],[2,1]]
在三个子列表的情况下
`[[A,B],[1,2], [c, d]]`
我想要输出
`[[A,B],[1,2], [c, d],
[A,B],[1,2], [d, c],
[A,B],[2,1], [c, d],
[A,B],[2,1], [d, c],
[B,A],[1,2], [c, d],
[B,A],[1,2], [d, c],
[B,A],[2,1], [c, d]
[B,A],[2,1], [d, c]]`
解决方案
使用itertools是这样做的正确方法(它是标准库的一部分,为什么不呢?)。例如:
from itertools import permutations, product
values = [['A', 'B'], [1, 2]]
sub_permutations = ([list(p) for p in permutations(l)] for l in values)
values_perms = [list(v) for v in product(*sub_permutations)]
def permutations(values):
if not values:
return
for i in range(len(values)):
for p in all_perms(values[1:]):
yield [*p[:i], values[0], *p[i:]]
def product(lists):
result = [[]]
for pool in lists:
result = [r + [p] for r in result for p in pool]
return result
然后我们可以使用它来实现相同的目标:
values = [['A', 'B'], [1, 2]]
values_perms = product(list(permutations(l)) for l in values)
但这会更慢,容易出现错误,这意味着需要维护更多的代码。我认为这里唯一有趣的事情是自己实现它,看看你最终会得到什么,然后简单地使用itertools
.
推荐阅读
- mongodb - 查找和删除文档中的重复键
- python - chart.js 中的散点图
- python - 使用 skimage 和 napari 将 blob_dog 中的 blob 添加到 3D 图像堆栈
- generative-adversarial-network - GAN 训练时图像质量突然下降
- sql - 当有 3000 列时如何以这种方式旋转表格
- python - 合并熊猫数据框中的列
- python - 如何使用元组查找字符串中的所有字母是否都在另一个字符串中?
- python - 如何保存我的课程以在另一个环境中加载
- javascript - 排序数组时如何正确使用getter
- google-bigquery - 查询 ARRAY (Bigquery) 中的 STRUCT 元素