使用字典计算列表中的项目 [英] Using a dictionary to count the items in a list

查看:40
本文介绍了使用字典计算列表中的项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Python 新手,我有一个简单的问题,比如我有一个项目列表:

['apple','red','apple','red','red','pear']

将列表项添加到字典并计算该项在列表中出现的次数的最简单方法是什么.

因此对于上面的列表,我希望输出为:

{'apple': 2, 'red': 3, 'pear': 1}

解决方案

在 2.7 和 3.1 中有特殊的 Counter 用于此目的的字典.

<预><代码>>>>从集合导入计数器>>>Counter(['apple','red','apple','red','red','pear'])计数器({'红色':3,'苹果':2,'梨':1})

I'm new to Python and I have a simple question, say I have a list of items:

['apple','red','apple','red','red','pear']

Whats the simpliest way to add the list items to a dictionary and count how many times the item appears in the list.

So for the list above I would like the output to be:

{'apple': 2, 'red': 3, 'pear': 1}

解决方案

in 2.7 and 3.1 there is special Counter dict for this purpose.

>>> from collections import Counter
>>> Counter(['apple','red','apple','red','red','pear'])
Counter({'red': 3, 'apple': 2, 'pear': 1})

这篇关于使用字典计算列表中的项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆