如何在Python的字典理解中创建值列表 [英] How to create a list of values in a dictionary comprehension in Python
问题描述
以一个非常简单的示例为例,它遍历一个句子并创建一个映射{x:y}
的字典,其中x
是表示单词长度的键,而y
是包含以下内容的句子中的单词列表x
字母量
Taking a very simple example of looping over a sentence and creating a dictionary which maps {x:y}
, where x
is a key representing the length of the words and y
is a list of words in the sentence that contain x
amount of letters
输入:
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']}
尝试创建一个值列表,但每次都覆盖它:
Here's an attempt that creates a list of values but overwrites it each time:
{len(x):[x] for x in mywords.split()}
{2: ['be'], 3: ['and'], 4: ['your'], 5: ['short'], 6: ['Monday']}
是否可以在Python中一行完成此操作?
Is it possible to do this in one line in Python?
推荐答案
可以,您可以使用sorted
+ groupby
,但是看起来并不好.
Sure, you can, using sorted
+ groupby
, but it doesn't look great.
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']}
PS,这是我对的答案(使用我为此推荐的defaultdict
) href ="https://stackoverflow.com/q/46820551/4909087">原始问题.
P.S., Here's my answer (using defaultdict
that I recommend over this) to the original question.
这篇关于如何在Python的字典理解中创建值列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!