我有一個字典,其中一個鍵是一個 id,值是一個字串串列。
我有興趣從中創建一個后續字典,以存盤每個字串的頻率。在這個新字典中,鍵是一個詞,值是它出現在原始字典中的串列數。
freq_dict = {}
for key, value in dict.items():
if word not in freq_dict:
freq_dict[word] = 0
freq_dict[word] = 1
continue
else:
freq_dict[word] = 1
continue
我在這里遇到的一個問題是,如果一個詞在串列中出現兩次,它將被計算兩次。為了解決這個問題,我嘗試使用break而不是continue,但是我永遠不會在每個串列中計算一個以上的單詞。
實作我想要的東西的好方法是什么?我雖然將set原始字典中的每個值都轉換為 a ,但這對于非常大的字典來說似乎不合理。
uj5u.com熱心網友回復:
您可以執行以下操作:
freq_dict = {}
for value in dct.values(): # don't call a variable dict
for word in value:
freq_dict[word] = freq_dict.get(word, 0) 1
如果您不想將串列中可能出現兩次的單詞計算兩次,只需將內部回圈更改為:
for word in set(value):
當然,有一些實用程式可以使這更容易:
from collections import Counter
from itertools import chain
freq_dict = Counter(chain(*dct.values()))
# freq_dict = Counter(chain(*map(set, dct.values())))
uj5u.com熱心網友回復:
您可以使用串列和字典理解。這是以下 dct1 的示例:
dct1 = {1: ["Bla", "Foo", "Foo", "Baz"], 2: ["Bla"], 3: ["Foo", "Baz"], 4: ["Baz"], 5: ["Foo"]}
使用以下代碼時,您會得到想要的結果:
#this flattens the dictionary to a one-level list where duplicates within one value list from dct1 are excluded
values_list = [entry for inner_list in [list(set(ls)) for ls in dct1.values()] for entry in inner_list]
#then you use a dictionary comprehension with the count function
dct2 = {string: values_list.count(string) for string in values_list}
dct2 然后給你以下內容:
{'Foo': 3, 'Bla': 2, 'Baz': 3}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/358754.html
