一般写法
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判断,而且 一次可以获取列表所有元素的个数

欢迎关注公众号,持续更新

python 的小技巧之统计list里面元素的个数

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-05-03
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2022-01-25
  • 2021-12-09
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-11-28
相关资源
相似解决方案