zoukankan      html  css  js  c++  java
  • python 的小技巧之统计list里面元素的个数

    一般写法
    def  count_list(std:list,tongji):
        i=0
        for item in std:
            if item==tongji:
                i+=1
        print(i)
    if __name__=='__main__':
        lists=[1,2,3,4,5,1,2,3,4,5,2,2,2,3,4]
        count_list(std=lists,tongji=2)
    新写法, python 3.5 之后
    def  count_list(std:list,tongji):
        from collections import Counter
        name=Counter()
        for  num in std:
            name[num]+=1
        print(name[tongji])
    if __name__=='__main__':
        lists=[1,2,3,4,5,1,2,3,4,5,2,2,2,3,4]
        count_list(std=lists,tongji=2)

    少了一个if判断,而且 一次可以获取列表所有元素的个数

  • 相关阅读:
    Linux删除文件相关命令
    Bing语句
    VS2013配置Winpcap
    node10-mongoose
    node09-cookie
    node08-express
    node07-http
    node06-path
    node05-fs
    node04-buffer
  • 原文地址:https://www.cnblogs.com/leiziv5/p/10988510.html
Copyright © 2011-2022 走看看