Python,试图在综合列表中生成字典

Python,试图在综合列表中生成字典,python,dictionary,list-comprehension,dictionary-comprehension,Python,Dictionary,List Comprehension,Dictionary Comprehension,如果我想从单词列表中使用理解和三元结构生成字典,我会遇到一些问题,需要帮助 字典应该在不需要额外模块导入的情况下生成,使用单词长度作为键,单词作为值。 我的问题是最简单的: l=['hdd', 'fdd', 'monitor', 'mouse', 'motherboard'] d={} for w in l : if len(w) in d : d[ len(w) ].append( w ) else : d[ len(w) ] = [ w ] #

如果我想从单词列表中使用理解和三元结构生成字典,我会遇到一些问题,需要帮助

字典应该在不需要额外模块导入的情况下生成,使用单词长度作为键,单词作为值。 我的问题是最简单的:

l=['hdd', 'fdd', 'monitor', 'mouse', 'motherboard']

d={}

for w in l :
    if len(w) in d  : d[ len(w) ].append( w )
    else            : d[ len(w) ] = [ w ]

# and dictionary inside list is OK:
print [d]
>>>[{11: ['motherboard'], 3: ['hdd', 'fdd'], 5: ['mouse'], 7: ['monitor']}]
然后试图使其全面:

d={}
print [ d[ len(w) ].append( w ) if len(w) in d else d.setdefault( len(w), [w] ) for w in l ]
>>>[['hdd', 'fdd'], None, ['monitor'], ['mouse'], ['motherboard']]

…这是行不通的。有什么帮助吗?

一切都很好,但您没有看到正确的东西:不要打印列表返回的内容。
它给出了
d[len(w)]的列表。附加(w)
通过列表理解产生,但您感兴趣的只是
d

l=['hdd', 'fdd', 'monitor', 'mouse', 'motherboard']

d={}
[ d[ len(w) ].append( w ) if len(w) in d else d.setdefault( len(w), [w] ) for w in l ]
print d
>>> {11: ['motherboard'], 3: ['hdd', 'fdd'], 5: ['mouse'], 7: ['monitor']}

这似乎是您所期望的。

这是因为您的列表将包含表达式的返回值。请尝试打印d[3]。在提示符中追加(123),然后查看。实际的字典
d
很好。请投票给我看看。呵呵!在这种情况下,理解只是语法:)