我有一个问题,不知道如何用 python 编码。
我有一个列表[10, 10, 10, 20, 20, 20, 30]
我希望它在这样的字典中
{"10": 1, "20": 3, "30" : 1}
我怎样才能做到这一点?
最佳答案
from collections import Counter
a = [10, 10, 10, 20, 20, 20, 30]
c = Counter(a)
# Counter({10: 3, 20: 3, 30: 1})
如果您真的想将键转换为字符串,那是一个单独的步骤:
dict((str(k), v) for k, v in c.iteritems())
这个类是 Python 2.7 的新类;对于早期版本,使用此实现:
http://code.activestate.com/recipes/576611/
编辑:把它放在这里因为 SO 不会让我将代码粘贴到评论中,
from collections import defaultdict
def count(it):
d = defaultdict(int)
for j in it:
d[j] += 1
return d
关于Python:将此列表转换为字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3956206/