簡體   English   中英

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

[英]How to create a list of values in a dictionary comprehension in Python

舉一個非常簡單的例子,循環一個句子並創建一個映射{x:y}的字典,其中x是表示單詞長度的鍵, y是句子中包含x個字母的單詞列表

輸入:

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

預計 Output:

{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']}

PS,這是我對原始問題答案 (使用我建議的defaultdict )。

不要試圖將所有內容都塞進一行,因為它不會可讀。 這是一個簡單,易於理解的解決方案,即使它需要兩行代碼:

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)

可以通過構建從 1 到單詞的最大長度的原始字符串來使用正則表達式,然后使用這些組並將它們的 position 迭代為單詞的大小。 最后使用 defaultdict as set 將組中的單詞添加到字典中。

text = "May your hot chocolate be delicious and sweet and your Monday be short"

max_len=0
for word in text.split():
    if len(word)>max_len: 
        max_len=len(word) 

pattern=[]

for index in range(1,max_len+1):
    index=str(index)
    pattern.append(r"(\b\w{"+"{index}".format(index=index)+r"}\b\s+)*")

pattern=''.join(pattern)
print(pattern)
groups=re.findall(pattern,text)
dict = defaultdict(set)
for group in groups:
    for position,value in enumerate(group):
        if len(value)>0:
             dict[position+1].add(value)

 print(dict)

output:

 defaultdict(<class 'set'>, {3: {'May ', 'hot ', 'and '}, 4: {'your '}, 9: {'delicious ', 'chocolate '}, 2: {'be '}, 5: {'sweet '}, 6: {'Monday '}})

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM