gpt4 book ai didi

python - 列表到Python中的字典转换

转载 作者:太空宇宙 更新时间:2023-11-04 02:30:53 24 4
gpt4 key购买 nike

我有一个包含以下名称的列表

d=[['Srini'], ['Rahul'], ['Mano'], ['Rahul'], ['Srini'], ['Mano], ['Srini'], ['Rahul']]

我正在使用下面的代码将列表转换为字典,该字典应将名称保存为键,将名称的计数保存为值。

dic={}
for words in d:
dic[words]= dic.get(words,0)+1
print(dic)

ERROR: TypeError Traceback (most recent call last) in () 1 dic={} 2 for words in d: ----> 3 dic[words]= dic.get(words,0)+1 4 print(dic)

TypeError: unhashable type: 'list'

最佳答案

列表是不可散列的。但是,您可以假设每个子列表都有一个元素并引用它:

dic={}
for words in d:
dic[words[0]]= dic.get(words[0], 0) + 1
print(dic)

请注意,顺便说一句,python 的 Counter 已经具有非常相似的功能:

from collections import Counter
print(Counter((i[0] for i in d)))

关于python - 列表到Python中的字典转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49210484/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com