python - 如何将列表转换为字典
问题描述
我想将列表转换为字典,其中键是列表中规定的整数,值是列表中数字的频率。例如,
列表 = [10,10,10,20,20,40,50]
那么字典看起来像,
dict = {'10':3,'20':2,'40':1,'50':1}。
这种转换的方法是什么?
解决方案
nlist = [10,10,10,20,20,40,50]
ndict = {}
for item in set(nlist):
ndict[item] = nlist.count(item)
创建 ndict:
{40: 1, 10: 3, 20: 2, 50: 1}