【python cookbook】找出序列中出现次数最多的元素
问题
《Python Cookbook》中有这么一个问题,给定一个序列,找出该序列出现次数最多的元素。
例如:
words = [
'look', 'into', 'my', 'eyes', 'look', 'into', 'my', 'eyes',
'the', 'eyes', 'the', 'eyes', 'the', 'eyes', 'not', 'around', 'the',
'eyes', "don't", 'look', 'around', 'the', 'eyes', 'look', 'into',
'my', 'eyes', "you're", 'under'
]
统计出words中出现次数最多的元素?
初步探讨
1、collections模块的Counter类
首先想到的是collections模块的Counter类,具体用法看这里!具体用法看这里!具体用法看这里!https://docs.python.org/3.6/l...,重要的事情强调三遍。
from collections import Counter words = [
'look', 'into', 'my', 'eyes', 'look', 'into', 'my', 'eyes',
'the', 'eyes', 'the', 'eyes', 'the', 'eyes', 'not', 'around', 'the',
'eyes', "don't", 'look', 'around', 'the', 'eyes', 'look', 'into',
'my', 'eyes', "you're", 'under'
] counter_words = Counter(words)
print(counter_words)
most_counter = counter_words.most_common(1)
print(most_counter)
关于most_common([n]):

2、根据dict键值唯一性和sorted()函数
import operator words = [
'look', 'into', 'my', 'eyes', 'look', 'into', 'my', 'eyes',
'the', 'eyes', 'the', 'eyes', 'the', 'eyes', 'not', 'around', 'the',
'eyes', "don't", 'look', 'around', 'the', 'eyes', 'look', 'into',
'my', 'eyes', "you're", 'under'
] dict_num = {}
for item in words:
if item not in dict_num.keys():
dict_num[item] = words.count(item) # print(dict_num) most_counter = sorted(dict_num.items(),key=lambda x: x[1],reverse=True)[0]
print(most_counter)
sorted函数:
传送门:https://docs.python.org/3.6/l...

iterable:可迭代类型;
key:用列表元素的某个属性或函数进行作为关键字,有默认值,迭代集合中的一项;
reverse:排序规则. reverse = True 降序 或者 reverse = False 升序,有默认值。
返回值:是一个经过排序的可迭代类型,与iterable一样。
这里,我们使用匿名函数key=lambda x: x[1]
等同于:
def key(x):
return x[1]
这里,我们利用每个元素出现的次数进行降序排序,得到的结果的第一项就是出现元素最多的项。
更进一步
这里给出的序列很简单,元素的数目很少,但是有时候,我们的列表中可能存在上百万上千万个元素,那么在这种情况下,不同的解决方案是不是效率就会有很大差别了呢?
为了验证这个问题,我们来生成一个随机数列表,元素个数为一百万个。
这里使用numpy Package,使用前,我们需要安装该包,numpy包下载地址:https://pypi.python.org/pypi/...。这里我们环境是centos7,选择numpy-1.14.2.zip (md5, pgp)进行下载安装,解压后python setup.py install
def generate_data(num=1000000):
return np.random.randint(num / 10, size=num)
np.random.randint(low[, high, size]) 返回随机的整数,位于半开区间 [low, high)
具体用法参考https://pypi.python.org/pypi
OK,数据生成了,让我们来测试一下两个方法所消耗的时间,统计时间,我们用time函数就可以。
#!/usr/bin/python
# coding=utf-8
#
# File: most_elements.py
# Author: ralap
# Data: 2018-4-5
# Description: find most elements in list
# from collections import Counter
import operator
import numpy as np
import random
import time def generate_data(num=1000000):
return np.random.randint(num / 10, size=num) def collect(test_list):
counter_words = Counter(test_list)
print(counter_words)
most_counter = counter_words.most_common(1)
print(most_counter) def list_to_dict(test_list):
dict_num = {}
for item in test_list:
if item not in dict_num.keys():
dict_num[item] = test_list.count(item) most_counter = sorted(dict_num.items(), key=lambda x: x[1], reverse=True)[0]
print(most_counter) if __name__ == "__main__":
list_value = list(generate_data()) t1 = time.time()
collect(list_value)
t2 = time.time()
print("collect took: %sms" % (t2 - t1)) t1 = t2
list_to_dict(list_value)
t2 = time.time()
print("list_to_dict took: %sms" % (t2 - t1))
以下结果是我在自己本地电脑运行结果,主要是对比两个方法相对消耗时间。

当数据比较大时,消耗时间差异竟然如此之大!下一步会进一步研究Counter的实现方式,看看究竟是什么魔法让他性能如此好。
参考资料
https://blog.csdn.net/xie_0723/article/details/51692806
【python cookbook】找出序列中出现次数最多的元素的更多相关文章
- 【python cookbook】【数据结构与算法】12.找出序列中出现次数最多的元素
问题:找出一个元素序列中出现次数最多的元素是什么 解决方案:collections模块中的Counter类正是为此类问题所设计的.它的一个非常方便的most_common()方法直接告诉你答案. # ...
- Python实用黑科技——找出序列里面出现次数最多的元素
需求: 如何从一个序列中快速获取出现次数最多的元素. 方法: 利用collections.Counter类可以解决这个问题,特别是他的most_common()方法更是处理此问题的最快途径.比如,现在 ...
- Java实现找出数组中重复次数最多的元素以及个数
/**数组中元素重复最多的数 * @param array * @author shaobn * @param array */ public static void getMethod_4(int[ ...
- [PY3]——找出一个序列中出现次数最多的元素/collections.Counter 类的用法
问题 怎样找出一个序列中出现次数最多的元素呢? 解决方案 collections.Counter 类就是专门为这类问题而设计的, 它甚至有一个有用的 most_common() 方法直接给了你答案 c ...
- 剑指Offer:找出数组中出现次数超过一半的元素
题目:找出数组中出现次数超过一半的元素 解法:每次删除数组中两个不同的元素,删除后,要查找的那个元素的个数仍然超过删除后的元素总数的一半 #include <stdio.h> int ha ...
- python之Counter类:计算序列中出现次数最多的元素
Counter类:计算序列中出现次数最多的元素 from collections import Counter c = Counter('abcdefaddffccef') print('完整的Cou ...
- Python中用max()筛选出列表中出现次数最多的元素
1 List = [1,2,3,4,2,3,2] # 随意创建一个只有数字的列表 2 maxTimes = max(List,key=List.count) # maxTimes指列表中出现次数最多的 ...
- python 找出字符串中出现次数最多的字母
# 请大家找出s=”aabbccddxxxxffff”中 出现次数最多的字母 # 第一种方法,字典方式: s="aabbccddxxxxffff" count ={} for i ...
- js常会问的问题:找出字符串中出现次数最多的字符。
一.循环obj let testStr = 'asdasddsfdsfadsfdghdadsdfdgdasd'; function getMax(str) { let obj = {}; for(le ...
随机推荐
- C#中Invoke的用法(转)
invoke和begininvoke 区别 一直对invoke和begininvoke的使用和概念比较混乱,这两天看了些资料,对这两个的用法和原理有了些新的认识和理解. 首先说下,invoke和beg ...
- 如何发布自定义的UI 组件库到 npmjs.com 并且编写 UI组件说明文档
记录基于 antd 封装业务组件并发布到npm 上的过程:(TS + React + Sass) 初始化项目: 1.yarn create react-app winyhui --typescript ...
- LODOP中的各种宽高和位置简短问答
LODOP中的位置边距,可查看本博客另一篇相关博文:LODOOP中的各种边距 打印项.整体偏移.可打区域.内部边距关于LODOP中的各种宽高,可查看本博文简短问答下方的正文:.该文其实有两个以前的相关 ...
- 如何查看crontab定时任务是否执行过 查看记录
命令的模式像下面这个: grep "script.php" /path/file.ext. 比如,下面的命令就是从/var/log/cron.log 检测cron任务是否有执行 c ...
- mysql的HA及openstack和k8s区别
数据库HA(Hight Availability) mysql自身支持主主/主备部署,多主(>2),一主多备 galera mariadb集群:多主相互备份 修改容器的启动配置 修改Docker ...
- 网站证书(SSL域名证书)常见格式使用
主流的Web服务软件通常都基于两种基础密码库:OpenSSL和Java 1.Tomcat.Weblogic.JBoss等系统是使用Java提供的密码库.通过Java的Keytool工具,生成Java ...
- beego框架(golang)学习过滤器(实现restful请求)
过滤器 在用beego做restful路由的时候,遇到了除了GTE.POST之外的HTTP请求,比如 PUT.PATCH.delete请求无法通过路由认证,报错误:405 METHOD NOT ALL ...
- Tensorflow-逻辑斯蒂回归
1.交叉熵 逻辑斯蒂回归这个模型采用的是交叉熵,通俗点理解交叉熵 推荐一篇文章讲的很清楚: https://www.zhihu.com/question/41252833 因此,交叉熵越低,这个策略就 ...
- [转帖]TPC-C基准测试之链路层优化
TPC-C基准测试之链路层优化 阿里数据库 6000万 TPMC的测试结构. http://www.itpub.net/2019/10/14/3436/ 作者:易鸿伟 闫建良 王光树 在 TPC-C ...
- TZOJ3133: 求对称点
#include<stdio.h> int main() { double a,b,c,d,e,f,g,h,i; while(~scanf("%lf %lf %lf %lf %l ...