python基于两个列表

时间:2016-09-12 06:19:56

标签: python list

早上好,

这可能很简单,但我刚开始使用python。学习: 是否有“更清洁”的方式基于两个列表创建嵌套字典:

person = ['mama.a','mama.b', 'mama.c',
         'mama.d', 'papa.a', 'papa.b']
kind = ['a', 'b', 'c', 'd']
combined = {}

# GOAL:
# {'mama': {'a': [], 'c': [], 'b': [], 'd': []}, 'papa': {'a': [], 'c': [], 'b': [], 'd': []}}

for human in [i.split('.')[0] for i in person]:
    combined[human] = {}
    for attrib in kind:
        combined[human][attrib] = []

3 个答案:

答案 0 :(得分:3)

{p.split('.')[0]: {k: [] for k in kind} for p in person}

答案 1 :(得分:0)

如何制作set名字呢?确保您只尝试将每一个添加到dict一次。

combined = {}
for n in set(p.split('.')[0] for p in person):
    combined[n] = {k:[] for k in kind}

这可能会成为一个怪物单行嵌套dict理解。虽然我不认为它会如此容易阅读。

或者您可以将set拆分到另一条线上。然后变成

pset = set(p.split('.')[0] for p in person)
pdict = {p: {k: [] for k in kind} for p in pset}

第二行与@Faiz Haldes回答相同。

答案 2 :(得分:0)

combined = {x.split('.')[0]:{i:[] for i in kind} for x in person} #if you require no check as to whether mama or papa contain a, b, c, or d
print combined

neutral = {i.split('.')[0]:[n.split('.')[1] for n in person if n.split('.')[0] == i.split('.')[0]] for i in person} #if you require a check
combined = {k:{v:[] for v in neutral[k]} for k in neutral}
print combined