所以我試圖使用字典理解來查找串列中所有單詞的出現次數,使用單詞的長度作為鍵,然后將單詞的長度作為值。
def words_lengths_map(text):
mod_text = ["hello", "this", "is", "a", "list", "of","words"]
dict1 = {len(k): k.count(k) for k in mod_text}
print(dict1)
這會產生正確的鍵,但我的值總是 1。我的預期輸出應該是 {5:2, 4:2, 2:2, 1:1}
謝謝
uj5u.com熱心網友回復:
你需要計算k的mod_text,而不是在本身(這將總是產生1)。
def words_lengths_map(text):
mod_text = text.split()
#['this','this','is', 'is', 'a']
dict1 = {len(k): mod_text.count(k) for k in mod_text}
print(dict1)
#{4: 2, 2: 2, 1: 1}
words_lengths_map("this this is is a")
uj5u.com熱心網友回復:
您無法通過理解有效地做到這一點,因為您需要對dict正在創建的同時進行參考。相反,您可以在普通回圈中更新計數器 dict,如果該鍵存在于 dict 中,則增加計數器的值,否則將其設定為 1:
counter = {}
for word in mod_text:
n = len(word)
if n in counter:
counter[n] = 1
else:
counter[n] = 1
print(counter)
# {5: 2, 4: 2, 2: 2, 1: 1}
uj5u.com熱心網友回復:
我可能會誤解你的問題,但你可以使用計數每次出現Counter的類collections模塊這里
例如
from collections import Counter
mod_text = ["hello", "this", "is", "a", "list", "of","words"]
lengths = [len(p) for p in mod_text] #Get the length of each word
c = Counter(lengths)
print(c)
#Counter({5: 2, 4: 2, 2: 2, 1: 1})
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/363153.html
下一篇:為什么我的函式沒有被完全列印?
