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

  • 相关阅读:
    osds have slow requests
    supervisor 管理 celery
    guacamole部署
    openstack IPV6
    修复VSAN无法看到主机磁盘
    kolla之docker私有仓库创建
    CSS日食与太阳碰撞
    vue-devtools必备工具
    VUE在BODY上绑定enter事件
    VUE输入框显示时自动聚焦
  • 原文地址:https://www.cnblogs.com/hester/p/6197449.html
Copyright © 2011-2022 走看看