码迷,mamicode.com
首页 > 编程语言 > 详细

Python统计列表中的重复项出现的次数的方法

时间:2018-01-19 14:15:26      阅读:153      评论:0      收藏:0      [点我收藏+]

标签:mys   containe   str   val   重复项   print   import   and   code   

对一个列表,比如[1,2,2,2,2,3,3,3,4,4,4,4],现在我们需要统计这个列表里的重复项,并且重复了几次也要统计出来

方法1:

1
2
3
4
mylist = [1,2,2,2,2,3,3,3,4,4,4,4]
myset = set(mylist)  #myset是另外一个列表,里面的内容是mylist里面的无重复 项
for item in myset:
  print("the %d has found %d" %(item,mylist.count(item)))

方法2:

1
2
3
4
5
6
List=[1,2,2,2,2,3,3,3,4,4,4,4]
a = {}
for i in List:
  if List.count(i)>1:
    a[i] = List.count(i)
print (a)

利用字典的特性来实现。

方法3:

1
2
3
>>> from collections import Counter
>>> Counter([1,2,2,2,2,3,3,3,4,4,4,4])
Counter({1: 5, 2: 3, 3: 2})

Python统计列表中的重复项出现的次数的方法

标签:mys   containe   str   val   重复项   print   import   and   code   

原文地址:https://www.cnblogs.com/royfans/p/8316060.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!