Python:将此列表转换为字典
我遇到了一个问题,不知道如何用python编写代码 我有一个Python:将此列表转换为字典,python,list,dictionary,formatting,Python,List,Dictionary,Formatting,我遇到了一个问题,不知道如何用python编写代码 我有一个列表[10,10,10,20,20,20,30] 我想把它放在这样一本字典里 {"10": 1, "20": 3, "30" : 1} 我怎样才能做到这一点?像这样 l = [10, 10, 10, 20, 20, 20, 30] uniqes = set(l) answer = {} for i in uniques: answer[i] = l.count(i) answer现在是您想要的词典 希望这有帮助 from
列表[10,10,10,20,20,20,30]
我想把它放在这样一本字典里
{"10": 1, "20": 3, "30" : 1}
我怎样才能做到这一点?像这样
l = [10, 10, 10, 20, 20, 20, 30]
uniqes = set(l)
answer = {}
for i in uniques:
answer[i] = l.count(i)
answer
现在是您想要的词典
希望这有帮助
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的新类;对于早期版本,请使用以下实现:
编辑:将其放在此处,因为这样我就不会将代码粘贴到注释中
from collections import defaultdict
def count(it):
d = defaultdict(int)
for j in it:
d[j] += 1
return d
另一种不使用
设置
或计数器
的方法:
d = {}
x = [10, 10, 10, 20, 20, 20, 30]
for j in x:
d[j] = d.get(j,0) + 1
编辑:对于大小为1000000、包含100个唯一项目的列表,此方法在我的笔记本电脑上运行只需0.37秒,而使用set
的答案需要2.59秒。对于只有10个唯一的项目,前一种方法需要0.36秒,而后一种方法只需要0.25秒
编辑:在我的笔记本电脑上使用
defaultdict
的方法需要0.18秒。在Python>=2.7中,您可以使用dict理解,如:
>>> 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}
?如果没有,这本词典是如何编纂的?与它们的键相关的值是什么?defaultdict的可能重复解决了所有问题如果这是一场性能竞赛,请检查我在答案中输入的defaultdict版本(怪我没有让我将其粘贴到这里),该版本的速度大约是原来的两倍。感谢您的评论。你完全正确:你的方法在我的笔记本电脑上运行了0.18秒。