代码工作得很好,但似乎不是很Pythonic如何改进这个字典的创建和从该字典创建组合?

2024-09-30 19:20:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我有两个字典,我用下面的代码把它们变成了一个列表字典。它是有效的,但它似乎是非Python的方式来做这件事。基本上,这是丑陋的,将需要更新,如果我的其他任何一个字典得到更新。你知道吗

KeyWeight = {x: MCNWeight[AttributeName[x]] for x in AttributeName.keys()}

list1 = []
list2 = []
list3 = []
list4 = []
list5 = []
list6 = []
list7 = []
list8 = []
list9 = []

for x, y in KeyWeight.iteritems():
if y == 1:
    list1.append(x)
elif y == 2:
    list2.append(x)
elif y == 3:
    list3.append(x)
elif y == 4:
    list4.append(x)
elif y == 5:
    list5.append(x)
elif y == 6:
    list6.append(x)
elif y == 7:
    list7.append(x)
elif y == 8:
    list8.append(x)
elif y == 9:
    list9.append(x)

KeyWeight = {1: list1, 2: list2, 3: list3, 4: list4, 5: list5, 6: list6, 7: list7, 8: list8, 9: list9}

之后,我有了一个非常粗略的嵌套for循环,它创建了该字典的所有可能的组合(如下所示)。它给出了我想要的结果,而且跑得很快,但我总觉得有更好的方法。你知道吗

非常感谢您的帮助!你知道吗

MasterMCN = []
MCNs = None


for each1 in KeyWeight[1]:
    MCNs = each1
    for each2 in KeyWeight[2]:
        MCNs2 = MCNs + '-' + each2
        for each3 in KeyWeight[3]:
            MCNs3 = MCNs2 + '-' + each3
            for each4 in KeyWeight[4]:
                MCNs4 = MCNs3 + '-' + each4
                for each5 in KeyWeight[5]:
                    MCNs5 = MCNs4 + '-' + each5
                    for each6 in KeyWeight[6]:
                        MCNs6 = MCNs5 + '-' + each6
                        for each7 in KeyWeight[7]:
                            MCNs7 = MCNs6 + '-' + each7
                            for each8 in KeyWeight[8]:
                                MCNs8 = MCNs7 + '-' + each8
                                for each9 in KeyWeight[9]:
                                    MCNs9 = MCNs8 + '-' + each9
                                    MasterMCN.append(MCNs9)

编辑: 多亏了摩西的回答,我才摆脱了讨厌的for循环。下面是更好的版本。你知道吗

for weight in sorted(KeyWeight.keys()):
    if not MasterMCN:
        MasterMCN = KeyWeight[weight]
    else:
        iter_prod = itertools.product(MasterMCN, KeyWeight[weight])
        MasterMCN = ['-'.join(x) for x in iter_prod]

Tags: infor字典elifappendlist2list1list3
2条回答

为什么不简单地使用一个列表列表,用y作为索引?你知道吗

您不需要预先分配这些列表,使用defaultdictlist作为值:

from collections import defaultdict

d = defaultdict(list)
for x, y in KeyWeight.iteritems():
   d[y].append(x)
KeyWeight = d

要从列表值创建组合,只需使用itertools.combinations。您可以使用这个相关的answer,它使用itertools.product并保留键值顺序作为指导。你知道吗

相关问题 更多 >