创建字典中每个元素(列表)的所有排列的列表 - Python

问题描述 投票:0回答:3

假设我有一个包含任意数量元素的字典,例如这里我们有3个元素。

{'key1':[1,2], 'key2':[3,4,5], 'key3':[6,7]}

我想从字典中的每个列表中一次取一个数字来生成这个列表:


[[1,3,6],[1,3,7],[1,4,6],[1,4,7],[1,5,6],[1,5,7],[2,3,6],[2,3,7],[2,4,6],[2,4,7],[2,5,6],[2,5,7]]

如何在 python 中执行这种类型的递归?

python list dictionary recursion permutation
3个回答
2
投票

如何使用

itertools.product

>>> import itertools
>>> d = {'key1': [1, 2], 'key2': [3, 4, 5], 'key3': [6, 7]}
>>> [list(t) for t in itertools.product(*d.values())]
[[1, 3, 6], [1, 3, 7], [1, 4, 6], [1, 4, 7], [1, 5, 6], [1, 5, 7], [2, 3, 6], [2, 3, 7], [2, 4, 6], [2, 4, 7], [2, 5, 6], [2, 5, 7]]
>>> # You can do this manually using three nested loops:
>>> [[a, b, c] for a in d['key1'] for b in d['key2'] for c in d['key3']]
[[1, 3, 6], [1, 3, 7], [1, 4, 6], [1, 4, 7], [1, 5, 6], [1, 5, 7], [2, 3, 6], [2, 3, 7], [2, 4, 6], [2, 4, 7], [2, 5, 6], [2, 5, 7]]

1
投票
import itertools as it

foo = {'key1':[1,2], 'key2':[3,4,5], 'key3':[6,7]}
list(it.product(*foo.values()))

出品:

[
  (1, 3, 6),
  (1, 3, 7),
  (1, 4, 6),
  (1, 4, 7),
  (1, 5, 6),
  (1, 5, 7),
  (2, 3, 6),
  (2, 3, 7),
  (2, 4, 6),
  (2, 4, 7),
  (2, 5, 6),
  (2, 5, 7),
]

0
投票

在不使用 itertools 的情况下,您可以使用函数遍历当前键的值,将每个值附加到组合并使用更新的组合和下一个索引调用自身。

def generate_permutations(d: dict):
    keys = list(d.keys())
    result = []

    def backtrack(combination, idx):
        if idx == len(keys):
            result.append(combination)
            return
        
        key = keys[idx]
        for val in d[key]:
            new_combination = combination + [val]
            backtrack(new_combination, idx + 1)
    
    backtrack([], 0)
    return result

d = {'key1': [1, 2], 'key2': [3, 4, 5], 'key3': [6, 7]}
permutations = generate_permutations(d)
print(permutations)

我更喜欢 itertools 版本,它更短,但这个版本可能更容易理解。

© www.soinside.com 2019 - 2024. All rights reserved.