资讯专栏INFORMATION COLUMN

【python cookbook】找出序列中出现次数最多的元素

AZmake / 2405人阅读

摘要:问题中有这么一个问题,给定一个序列,找出该序列出现次数最多的元素。例如统计出中出现次数最多的元素初步探讨模块的类首先想到的是模块的类,具体用法看这里具体用法看这里具体用法看这里,重要的事情强调三遍。

问题

《Python Cookbook》中有这么一个问题,给定一个序列,找出该序列出现次数最多的元素。
例如:

</>复制代码

  1. words = [
  2. "look", "into", "my", "eyes", "look", "into", "my", "eyes",
  3. "the", "eyes", "the", "eyes", "the", "eyes", "not", "around", "the",
  4. "eyes", "don"t", "look", "around", "the", "eyes", "look", "into",
  5. "my", "eyes", "you"re", "under"
  6. ]

统计出words中出现次数最多的元素?

初步探讨

1、collections模块的Counter类
首先想到的是collections模块的Counter类,具体用法看这里!具体用法看这里!具体用法看这里!https://docs.python.org/3.6/l...,重要的事情强调三遍。

</>复制代码

  1. from collections import Counter
  2. words = [
  3. "look", "into", "my", "eyes", "look", "into", "my", "eyes",
  4. "the", "eyes", "the", "eyes", "the", "eyes", "not", "around", "the",
  5. "eyes", "don"t", "look", "around", "the", "eyes", "look", "into",
  6. "my", "eyes", "you"re", "under"
  7. ]
  8. counter_words = Counter(words)
  9. print(counter_words)
  10. most_counter = counter_words.most_common(1)
  11. print(most_counter)

关于most_common([n]):

2、根据dict键值唯一性和sorted()函数

</>复制代码

  1. import operator
  2. words = [
  3. "look", "into", "my", "eyes", "look", "into", "my", "eyes",
  4. "the", "eyes", "the", "eyes", "the", "eyes", "not", "around", "the",
  5. "eyes", "don"t", "look", "around", "the", "eyes", "look", "into",
  6. "my", "eyes", "you"re", "under"
  7. ]
  8. dict_num = {}
  9. for item in words:
  10. if item not in dict_num.keys():
  11. dict_num[item] = words.count(item)
  12. # print(dict_num)
  13. most_counter = sorted(dict_num.items(),key=lambda x: x[1],reverse=True)[0]
  14. print(most_counter)

sorted函数:
传送门:https://docs.python.org/3.6/l...

iterable:可迭代类型;
key:用列表元素的某个属性或函数进行作为关键字,有默认值,迭代集合中的一项;
reverse:排序规则. reverse = True 降序 或者 reverse = False 升序,有默认值。
返回值:是一个经过排序的可迭代类型,与iterable一样。

这里,我们使用匿名函数key=lambda x: x[1]
等同于:

</>复制代码

  1. def key(x):
  2. return x[1]

这里,我们利用每个元素出现的次数进行降序排序,得到的结果的第一项就是出现元素最多的项。

更进一步

这里给出的序列很简单,元素的数目很少,但是有时候,我们的列表中可能存在上百万上千万个元素,那么在这种情况下,不同的解决方案是不是效率就会有很大差别了呢?
为了验证这个问题,我们来生成一个随机数列表,元素个数为一百万个。
这里使用numpy Package,使用前,我们需要安装该包,numpy包下载地址:https://pypi.python.org/pypi/...。这里我们环境是centos7,选择numpy-1.14.2.zip (md5, pgp)进行下载安装,解压后python setup.py install

</>复制代码

  1. def generate_data(num=1000000):
  2. return np.random.randint(num / 10, size=num)

np.random.randint(low[, high, size]) 返回随机的整数,位于半开区间 [low, high)
具体用法参考https://pypi.python.org/pypi

OK,数据生成了,让我们来测试一下两个方法所消耗的时间,统计时间,我们用time函数就可以。

</>复制代码

  1. #!/usr/bin/python
  2. # coding=utf-8
  3. #
  4. # File: most_elements.py
  5. # Author: ralap
  6. # Data: 2018-4-5
  7. # Description: find most elements in list
  8. #
  9. from collections import Counter
  10. import operator
  11. import numpy as np
  12. import random
  13. import time
  14. def generate_data(num=1000000):
  15. return np.random.randint(num / 10, size=num)
  16. def collect(test_list):
  17. counter_words = Counter(test_list)
  18. print(counter_words)
  19. most_counter = counter_words.most_common(1)
  20. print(most_counter)
  21. def list_to_dict(test_list):
  22. dict_num = {}
  23. for item in test_list:
  24. if item not in dict_num.keys():
  25. dict_num[item] = test_list.count(item)
  26. most_counter = sorted(dict_num.items(), key=lambda x: x[1], reverse=True)[0]
  27. print(most_counter)
  28. if __name__ == "__main__":
  29. list_value = list(generate_data())
  30. t1 = time.time()
  31. collect(list_value)
  32. t2 = time.time()
  33. print("collect took: %sms" % (t2 - t1))
  34. t1 = t2
  35. list_to_dict(list_value)
  36. t2 = time.time()
  37. print("list_to_dict took: %sms" % (t2 - t1))

以下结果是我在自己本地电脑运行结果,主要是对比两个方法相对消耗时间。

当数据比较大时,消耗时间差异竟然如此之大!下一步会进一步研究Counter的实现方式,看看究竟是什么魔法让他性能如此好。

参考资料

https://blog.csdn.net/xie_072...

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/41511.html

相关文章

  • Python3 CookBook | 数据结构和算法(二)

    摘要:以下测试代码全部基于查找最大或最小的个元素工作中有时会遇到这样的需求,取出数据中前面的值,或者最后的值。大家如果对堆数据结构感兴趣的话,可以继续进行深入研究,由于我了解的并不深,也没办法再展开了。 文章首发于知乎专栏,欢迎关注。https://zhuanlan.zhihu.com/py... 以下测试代码全部基于 Python3 1、查找最大或最小的 N 个元素 工作中有时会遇到这样的...

    geekidentity 评论0 收藏0
  • Python每日一练0009

    摘要:问题怎样找出一个序列中出现次数最多的元素解决方案使用库中的对象可以方便的求出现次数最多的前个元素直接使用成员函数就好了,例如输出讨论对象是的子类,事实上内部存储也是按照字典存储的,这里的就是次数,所以对象支持对象的所有操作每一个对象初始化 问题 怎样找出一个序列中出现次数最多的元素? 解决方案 使用collections库中的Counter对象可以方便的求出现次数最多的前N个元素 直接...

    yiliang 评论0 收藏0
  • Python实用技法第11篇:找出序列出现次数多的元素

    摘要:上一篇文章实用技法第篇对切片命名下一篇文章实用技法第篇通过公共键对字典列表排序需求 上一篇文章:Python实用技法第10篇:对切片命名下一篇文章:Python实用技法第12篇:通过公共键对字典列表排序:itemgetter 1、需求

    superw 评论0 收藏0
  • C语言——一维数组算法问题

    摘要:算法描述向数组中输入元素定义一个新数组将数组中的元素倒序存放将数组正序输出,注意结尾无空格的格式问题。最后打印出来数组中的元素,也就是非共有值,此处注意格式问题。 问题1:将数组中的数逆序存放 本题要求编写程序,将给定的n个整数存入数组中,将数组中的这n个数逆序存放, 再按顺序输出数组中的元...

    lifesimple 评论0 收藏0
  • Python实用技法第10篇:对切片命名

    摘要:上一篇文章实用技法第篇从序列中移除重复项且保持元素间顺序不变下一篇文章实用技法第篇找出序列中出现次数最多的元素需求 上一篇文章:Python实用技法第9篇:从序列中移除重复项且保持元素间顺序不变下一篇文章:Python实用技法第11篇:找出序列中出现次数最多的元素 1、需求

    kohoh_ 评论0 收藏0

发表评论

0条评论

最新活动
阅读需要支付1元查看
<