如何在Python中创建词典理解中的值列表
问题描述:
以循环遍历一个句子并创建一个映射{x:y}
的词典为例,其中x
是表示词长度的键,y
是列表在句子中包含x
量的字母的单词的如何在Python中创建词典理解中的值列表
输入:
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做到这一条线?
答
当然,你可以使用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。
答
不要试图在一行中塞满一切,它将不可读。这是一个简单的,易于理解的解决方案,即使这需要几行:
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)
我同意这是“正确的方式”来做到这一点......但很显然侵犯了他一个线条件.... –
@JoranBeasley作为参考,这个问题源于[另一个问题](https://stackoverflow.com/q/46820551/4909087),和我[回答](https://stackoverflow.com/ a/46820587/4909087)就是这样。 –
@cᴏʟᴅsᴘᴇᴇᴅ我以为当他最初发布它时,他只是在回答你的问题。我希望能够理解,我在另一个答案中看到了这个解决方案,但我试图在一行中尝试 - 结果表明1号班轮比预期的要复杂一些 – AK47