【发布时间】:2018-03-30 22:47:29
【问题描述】:
举一个非常简单的例子,循环一个句子并创建一个映射{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 中是否可以在一行中做到这一点?
【问题讨论】:
标签: python list dictionary dictionary-comprehension