今天在写模拟购物车的时候需要统计列表中相同元素出现的次数,百度一顿搜搜终于找到比较
好的方法,
第一种:
>>> 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