• 技术文章 >常见问题 >Python常见问题

    python如何查询列表中不同元素个数?

    yangyang2020-05-18 14:53:59原创3723

    python中可以使用collections.Counter(list)方法查询列表中不同元素个数。

    Counter中文意思是计数器,也就是我们常用于统计的一种数据类型,在使用Counter之后可以让我们的代码更加简单易读。

    示例:

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    #统计词频

    colors = ['red', 'blue', 'red', 'green', 'blue', 'blue']

    result = {}

    for color in colors:

        if result.get(color)==None:

            result[color]=1

        else:

            result[color]+=1

    print (result)

    #{'red': 2, 'blue': 3, 'green': 1}

    用Counter实现:

    1

    2

    3

    4

    from collections import Counter

    colors = ['red', 'blue', 'red', 'green', 'blue', 'blue']

    c = Counter(colors)

    print (dict(c))

    输出结果

    {'red': 2, 'blue': 3, 'green': 1}

    更多Python知识请关注Python自学网

    专题推荐:python
    上一篇:如何用Python画一颗小树? 下一篇:如何用Python编写一副扑克牌?

    相关文章推荐

    • Python中质数怎么找?• 如何把python文件做成exe文件• Python使用什么划分语句块?• 怎么查看python.exe文件在哪?

    全部评论我要评论

    © 2021 Python学习网 苏ICP备2021003149号-1

  • 取消发布评论
  • 

    Python学习网