zoukankan      html  css  js  c++  java
  • Python统计列表中的重复项出现的次数的方法

    本文实例展示了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

    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])

  • 相关阅读:
    leetcode78 Subsets
    leetcode76 Minimum Window Substring
    leetcode73 Set Matrix Zeroes
    leetcode70 Climbing Stairs
    leetcode50 Pow(x, n)
    leetcode49 Group Anagrams
    leetcode48 Rotate Image
    正则表达式及字符处理
    RPM软件包管理.作业
    yum管理RPM包.作业
  • 原文地址:https://www.cnblogs.com/hester/p/6197449.html
Copyright © 2011-2022 走看看