【发布时间】:2015-02-25 11:27:14
【问题描述】:
如果我想使用内部理解和三元从单词列表生成字典,我会遇到一些问题并需要帮助。
应该在没有额外模块导入的情况下生成字典,使用单词长度作为键,单词作为值。 这是我最简化的问题:
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']]
...这不起作用。有什么帮助吗?
【问题讨论】:
-
这是因为您的列表将包含您的表达式的返回值。在提示符中尝试
print d[3].append(123)看看。实际字典d很好。 -
点赞让我看看。
标签: python dictionary list-comprehension dictionary-comprehension