1

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

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

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']]

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

4

1 回答 1

1

Everything is fine, but you are not looking at the right thing : do not print what the list comprehension returns.
It gives you the list of the d[ len(w) ].append( w ) yield by the list comprehension but what you are interested in is just 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']}

Which seems to be what you expect.

于 2015-02-25T11:37:11.453 回答