2017-10-18 73 views
1

以循環遍歷一個句子並創建一個映射{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做到這一條線?

回答

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

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) 
+0

我同意這是「正確的方式」來做到這一點......但很顯然侵犯了他一個線條件.... –

+0

@JoranBeasley作爲參考,這個問題源於[另一個問題](https://stackoverflow.com/q/46820551/4909087),和我[回答](https://stackoverflow.com/ a/46820587/4909087)就是這樣。 –

+0

@cᴏʟᴅsᴘᴇᴇᴅ我以爲當他最初發布它時,他只是在回答你的問題。我希望能夠理解,我在另一個答案中看到了這個解決方案,但我試圖在一行中嘗試 - 結果表明1號班輪比預期的要複雜一些 – AK47