我有一个问题,不知道如何在Python中编写代码。
我有一个list[10, 10, 10, 20, 20, 20, 30]
我希望它成为一个像这样的字典
{"10": 1, "20": 3, "30" : 1}
我该如何实现这个?
我有一个问题,不知道如何在Python中编写代码。
我有一个list[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
另一种不使用set
或Counter
的方法:
d = {}
x = [10, 10, 10, 20, 20, 20, 30]
for j in x:
d[j] = d.get(j,0) + 1
set
的答案需要2.59秒。对于仅有10个独特项的情况,前一种方法需要0.36秒,而后一种方法仅需要0.25秒。defaultdict
的方法在我的笔记本电脑上只需0.18秒。像这样
l = [10, 10, 10, 20, 20, 20, 30]
uniqes = set(l)
answer = {}
for i in uniques:
answer[i] = l.count(i)
answer
现在是您想要的字典
希望这可以帮到您
>>> l = [10, 10, 10, 20, 20, 20, 30]
>>> {x: l.count(x) for x in l}
{10: 3, 20: 3, 30: 1}
不是最快的方式,但非常适合小型列表
或者,受inspectorG4dget启发,这个更好:
{x: l.count(x) for x in set(l)}
{"10": 3, "20":3, "30":1}
吗?如果不是,那么这个字典是如何编制的?键对应的值是什么? - Anthony Forloney