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
好的方法,
第一种:
>>> 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
相关文章推荐
- 笨办法学Python学习笔记 练习26
- 笨办法学Python学习笔记 练习25
- python的安装与运行
- Python 整理一
- python 集合
- python学习之路(1)
- python子进程模块subprocess详解与应用实例 之一
- Python 正则表达试
- python的输入输出
- 用ladon框架封装Python为Webservice接口以及调用接口的方法
- Python 2.5.10 sorted
- Python字符串原理剖析------万恶的+号
- 【LeetCode】【Python题解】Single Number & Maximum Depth of Binary Tree
- 关于Numpy,Scipy,Scikit-learn的查询文档
- python二维数组
- selenium-webdriver(python) (十) 如何处理下拉框
- python socket编程详细介绍
- python数据类型转换
- Python编程的例子----股票数据接口
- python 的内嵌time模板翻译及说明[转]