如何在Python中的字典理解中创建值列表

时间:2017-10-18 23:27:55

标签: python list dictionary dictionary-comprehension

一个非常简单的循环句子并创建一个映射{x:y}的字典的示例,其中x是表示单词长度的键,y是一个列表句子中包含x字母数量的单词

输入:

mywords = "May your coffee be strong and your Monday be short"

预期产出:

{2: ['be', 'be'], 3: ['May', 'and'], 4: ['your', 'your'], 5: ['short'], 6: ['coffee', 'strong', 'Monday']}

这是尝试创建值列表但每次都覆盖它:

{len(x):[x] for x in mywords.split()}
{2: ['be'], 3: ['and'], 4: ['your'], 5: ['short'], 6: ['Monday']}

是否可以在Python的一行中执行此操作?

2 个答案:

答案 0 :(得分:2)

当然,您可以使用sorted + groupby,但它看起来并不好。

from itertools import groupby
d = dict([(k, list(g)) for k, g in groupby(sorted(mywords.split(), key=len), key=len)])

print(d)
{2: ['be', 'be'],
 3: ['May', 'and'],
 4: ['your', 'your'],
 5: ['short'],
 6: ['coffee', 'strong', 'Monday']}

P.S。,这是我的answer(我建议使用defaultdict)到original question

答案 1 :(得分:2)

不要尝试将所有东西塞进一行,它不会被读取。这是一个简单易懂的解决方案,即使它需要几行:

from collections import defaultdict

mywords = "May your coffee be strong and your Monday be short"    
ans = defaultdict(list)

for word in mywords.split():
    ans[len(word)].append(word)