【发布时间】:2022-01-10 18:01:49
【问题描述】:
如何转换此列表列表
[['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 中做到这一点,而不需要任何额外的库等。 谢谢
【问题讨论】:
-
列表不能用作字典键。
-
如果我首先将它转换为一个元组列表,所以我有类似 [('of', 'god'), ('of', 'his'), ('of', '她'), ('of', '神')]?
标签: python list dictionary typeerror