繁体   English   中英

使用理解创建包含列表值的字典

[英]creating dictionary containing list values using a comprehension

在python中,我希望使用具有字符串的键和作为列表的值的理解来创建字典。 我无法弄清楚的是,如何将元素附加到这些列表中。 例如,考虑我的以下尝试:

{c: [].append(x[0]) for x in g16.nodes(data=True) for c in colors if x[1]['color'] == c}

g16.nodes(data = True)给出一个对列表,其中第一个元素是一个字符串,第二个元素是一个只指定颜色的字典。 如上所述,我希望将这个结构变成一个字典,其中键给出颜色,值是具有这种颜色的字符串列表。

如果您有解决方案,或者有更好的方法,请告诉我!

谢谢你的帮助。

你正试图这样做:

{c: [x[0] for x in g16.nodes(data=True) if x[1]['color'] == c] for c in colors}

但它并不是非常有效,因为你为每种颜色循环g16.nodes(data=True)一次

这样的事情会更好

d = {c: [] for c in colors}
for x in g16.nodes(data=True):
    k = x[1]['color']
    if k in d:
        d[k].append(x[0])

如果你知道k总是用colors ,你可以简化为

d = {c: [] for c in colors}
for x in g16.nodes(data=True):
    d[x[1]['color']].append(x[0])

使用对列表键的字典的理解并不是很好。 如果您可以尝试这样做可能会更容易:

假设g16.nodes(data=True)就像

[('key1', {'color': 'black'}), ('key2', {'color': 'green')]

并且color键存在,你可以试试这个:

from collections import defaultdict
gen = ((k, c['color']) for k, c in g16.nodes(data=True) if c['color'] in colors)
results = defaultdict(list)
for key, color in gen:
    results[color].append(key)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM