如何从字典中创建每个键的排列?

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

说我有一个带有指定值的字母字典:

  dictionary = {"l":"smias", "k":"swdw", 'm':'blala'}

我如何创建没有重复的键排列,并将其作为元组返回,像这样?

  mytuple = ((l,k),(l,m),(k,m))
python graph adjacency-matrix adjacency-list
2个回答
0
投票

您的示例是组合,而不是排列。您可以通过itertools

获得
from itertools import combinations

d = {"l":"smias", "k":"swdw", 'm':'blala'}

tuple(combinations(d, r=2))
# (('l', 'k'), ('l', 'm'), ('k', 'm'))

或排列:

from itertools import permutations

d = {"l":"smias", "k":"swdw", 'm':'blala'}

tuple(permutations(d, r=2))
# (('l', 'k'), ('l', 'm'), ('k', 'l'), ('k', 'm'), ('m', 'l'), ('m', 'k'))

0
投票

您可以在不使用库的情况下尝试此操作。

def combinations(lst, length, idx, cur, res):
    # length: length of each item in combinations
    if length == 0:
        res.append(tuple(cur))
        return
    for i in range(idx, len(lst)):
        combinations(lst, length - 1, i + 1, cur + [lst[i]], res)

res = []
dictionary = {"l":"smias", "k":"swdw", 'm':'blala'}
combinations(list(dictionary.keys()), 2, 0, [], res)
mytuple = tuple(res)
# (('l', 'k'), ('l', 'm'), ('k', 'm'))
© www.soinside.com 2019 - 2024. All rights reserved.