• 周五. 4月 26th, 2024

5G编程聚合网

5G时代下一个聚合的编程学习网

热门标签

在Python中有四种方法,可以用来统计列表中的重复项出现的次数

admin

11月 28, 2021

本文实例展示了Python统计列表中的重复项出现的次数的方法,是一个很实用的功能,适合Python初学者学习借鉴。

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

方法1

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

'''
学习中遇到问题没人解答?小编创建了一个Python学习交流群:531509025
寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书!
'''
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

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

方法4

这里再增补一个只用列表实现的方法:

l=[1,4,2,4,2,2,5,2,6,3,3,6,3,6,6,3,3,3,7,8,9,8,7,0,7,1,2,4,7,8,9]

count_times = []
for i in l :
count_times.append(l.count(i))

m = max(count_times)
n = l.index(m)

print (l[n])

《在Python中有四种方法,可以用来统计列表中的重复项出现的次数》有2个想法
  1. Wow, amazing blog format! How lengthy have you ever been blogging for?
    you made running a blog glance easy. The full glance of your website is magnificent,
    let alone the content! You can see similar here dobry sklep

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注