Python 如何计算列表中的元素并返回dict?
假设我有一张Python 如何计算列表中的元素并返回dict?,python,dictionary,Python,Dictionary,假设我有一张 L = ['hello', 'hello', 'hi', 'hello', 'hello'] 我想数一数列表中有多少个'hello'和'hi'。因此结果是'hello':4,'hi':1 如何以字典形式实现此结果?我的教授还没有讨论过这个问题,所以我不知道如何从列表转换到字典。不使用外部模块,只使用计数,尽管使用dict理解会有一些冗余: d = {itm:L.count(itm) for itm in set(L)} 如果允许您使用外部模块,并且不需要自己实现所有功能,那么您
L = ['hello', 'hello', 'hi', 'hello', 'hello']
我想数一数列表中有多少个'hello'
和'hi'
。因此结果是'hello':4
,'hi':1
如何以字典形式实现此结果?我的教授还没有讨论过这个问题,所以我不知道如何从列表转换到字典。不使用外部模块,只使用
计数,尽管使用dict理解会有一些冗余:
d = {itm:L.count(itm) for itm in set(L)}
如果允许您使用外部模块,并且不需要自己实现所有功能,那么您可以使用通过模块交付的Python:
给你:
dict_items([('hi', 1), ('hello', 4)])
Counter({'hello': 4, 'hi': 1})
编辑:
如评论中所述,您可以使用这样一种更简单的方法:
#!/usr/bin/env python3
# coding: utf-8
from collections import Counter
word_list = ['hello', 'hello', 'hi', 'hello', 'hello']
c = Counter(word_list)
print(c)
给你:
dict_items([('hi', 1), ('hello', 4)])
Counter({'hello': 4, 'hi': 1})
使用计数器:
>>> from collections import Counter
>>> def how_many(li): return Counter(li)
...
>>> how_many(['hello', 'hello', 'hi', 'hello', 'hello'])
Counter({'hello': 4, 'hi': 1})
或者,您可以执行以下操作:
>>> li=['hello', 'hello', 'hi', 'hello', 'hello']
>>> {e:li.count(e) for e in set(li)}
{'hi': 1, 'hello': 4}
或者,您可以执行以下操作:
>>> di={}
>>> for e in li:
... di[e]=di.get(e, 0)+1
...
>>> di
{'hi': 1, 'hello': 4}
你听说过计数器吗?
?这可能不符合家庭作业的精神。你必须向我们展示解决这个问题的一些尝试,因为这不是家庭作业完成服务。不过,我不是在要求代码回答。我只是想看看是否有任何内置函数(例如计数器,如上面提到的Avinash)。使用dict理解有一些冗余,但它可能是d={itm:L.count(itm)for itm in L}
我不理解否决票,这不是一个坏答案,只是一个不同的答案。你的第一个答案正是我想要的。谢谢-1:{itm:L.count(itm)for itm in L}
只需使用更新的计数擦除dict键,直到重复项的最终唯一列表值。浪费和缓慢。您应该对集合(L)中的itm执行{itm:L.count(itm)}
,这样列表中的每个唯一条目只执行一次计数步骤。@thewolf:这不是我答案的一部分,而是由David Zemens添加的。由于您的评论,我更新了我的答案。谢谢你的改进。