您的位置:首页 > 编程语言 > Python开发

python 统计列表相同值重复次数

2016-01-13 16:20 495 查看
今天在写模拟购物车的时候需要统计列表中相同元素出现的次数,百度一顿搜搜终于找到比较
好的方法,

第一种:

>>> test_list = ['a',0,'a',1,'a',0,1]
>>> test_set = set(test_list)
>>> for i in test_set:
... print('values %s times %d' % (i,test_list.count(i)))
...
values a times 3
values 0 times 2
values 1 times 2

第二种:

>>> from collections import Counter
>>> test_list = ['a',0,'a',1,'a',0,1]
>>> num = Counter(test_list)
>>> num
Counter({'a': 3, 0: 2, 1: 2})
>>> num[0]
2
>>> num[1]
2
>>> num['a']
3

第三种:
>>> test_list = ['a',0,'a',1,'a',0,1,6]
>>> test_dict = {}
>>> for i in test_list:
... if test_list.count(i) >= 1:
... test_dict[i] = test_list.count(i)
...
>>> print(test_dict)
{0: 2, 'a': 3, 6: 1, 1: 2}

注:本文博引 http://blog.sina.com.cn/s/blog_670445240102v8aj.html 本文出自 “纷繁中享受技术的简单喜悦” 博客,请务必保留此出处http://51enjoy.blog.51cto.com/8393791/1734667
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: