如何轉換此串列串列
[['shall', 'prove'], ['shall', 'not'], ['shall', 'go'], ['shall', 'fight'], ['shall', 'fight'], ['shall', 'fight'], ['shall', 'defend'], ['shall', 'fight'], ['shall', 'fight'], ['shall', 'fight'], ['shall', 'fight'], ['shall', 'never']]
進入一個字典,該字典計算每個元素在串列中出現的次數?
即['shall', 'fight']出現7次
我試過這樣的事情
def word_counter(input_str):
counts = {}
for w in input_str:
counts[w] = counts.get(w, 0) 1
items = counts.items()
word_counter([['of', 'god'], ['of', 'his'], ['of', 'her'], ['of', 'god']])
我希望輸出類似于
{['of', 'god']: 2, ['of', 'his']: 2, ['of', 'her']: 1}
但我明白了
TypeError: unhashable type: 'list'
任何幫助將非常感激!理想情況下,我想在基本 Python 中執行此操作,而無需任何額外的庫等。謝謝
uj5u.com熱心網友回復:
您可以將串列元素轉換為str這樣您就可以將它們用作字典中的鍵:
def word_counter(input_lst: list[list[str]]) -> dict[str, int]:
counts: dict[str, int] = {}
for pair in input_lst:
pair = str(pair)
if pair in counts:
counts[pair] = 1
else:
counts[pair] = 1
return counts
# Output: {"['of', 'god']": 2, "['of', 'his']": 1, "['of', 'her']": 1}
print(word_counter([['of', 'god'], ['of', 'his'], ['of', 'her'], ['of', 'god']]))
如果需要,只需將它們轉換回串列。
uj5u.com熱心網友回復:
串列是可變物件,它們不能被散列,因此不能用作字典中的鍵。您可以使用類似于串列的不可變序列的元組。另外,計數已經在pythoncollections的標準庫模塊中實作了(你不必安裝任何額外的庫)。下面是一個例子:
import collections
original = [('shall', 'prove'), ('shall', 'not'), ('shall', 'go'), ('shall', 'fight'),
('shall', 'fight'), ('shall', 'fight'), ('shall', 'defend'), ('shall', 'fight'),
('shall', 'fight'), ('shall', 'fight'), ('shall', 'fight'), ('shall', 'never')]
counts = collections.Counter(original)
# counts is a Counter object which is a subclass of dict, but
# if you want a normal dict add the line below
counts_as_dict = dict(counts)
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/375716.html
下一篇:如何按串列中的位置列印函式?
