2017-10-28 139 views
0

我想把一个列表放入一个字典中,并计算列表中每个单词的出现次数。我不明白的唯一问题是当我使用更新函数时,它需要x作为字典键,当我希望x是list_的x值时。我是新来的Python,所以任何意见表示赞赏。如果你想要的项目列表转换为包含的list_entry: number_of_occurences映射字典的简单方式感谢我如何操纵键循环更新字典

list_ = ["hello", "there", "friend", "hello"] 
d = {} 
for x in list_: 
    d.update(x = list_.count(x)) 

回答

3

使用Counter对象。

>>> from collections import Counter 
>>> words = ['hello', 'there', 'friend', 'hello'] 
>>> c = Counter(words) 

>>> print(c) 
Counter({'hello': 2, 'there': 1, 'friend': 1}) 

>>> print(dict(c)) 
{'there': 1, 'hello': 2, 'friend': 1} 
+0

哇,不知道你可以做到这一点。谢谢! – user3152311

3

的选项将使用字典解析与list.count()这样的:

list_ = ["hello", "there", "friend", "hello"] 
d = {item: list_.count(item) for item in list_} 

输出:

>>> d 
{'hello': 2, 'there': 1, 'friend': 1} 

但是,最好的选择应该在@ AK47的溶液中使用collections.Counter()

+0

这也工作了,谢谢:) – user3152311