python中计算一个列表中连续相同的元素个数方法
作者:老胡当道卧 时间:2021-02-04 22:59:23
最简单的例子:
a = [1,1,1,1,2,2,2,3,3,1,1,1,3]
# 问:计算a中最多有几个连续的1
很明显,答案是4
如果用代码实现,最先想到的就是itertools:
import itertools
a = [1,1,1,1,2,2,2,3,3,1,1,1,3]
print max([len(list(v)) for k,v in itertools.groupby(a)])
但是如果不想用itertools呢?
可以尝试以下的办法,效率还比itertools高一个数量级!
import random
import time
import itertools
random.seed(0)
a = ['1' if random.random()>0.4 else ' ' for i in range(1000000)]
t = time.time()
print max([len(x) for x in ''.join(a).split()])
print time.time()-t
t = time.time()
print max([len(list(v)) for k,v in itertools.groupby(a)])
print time.time()-t
#####
# 27
# 0.050999879837
# 27
# 0.450000047684
来源:https://blog.csdn.net/sinat_27339001/article/details/79449767
标签:python,列表,连续,元素
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Python3中对range()逆序的解释
2023-03-26 10:27:59
在Python中使用Neo4j的方法
2023-01-16 04:12:39
![](https://img.aspxhome.com/file/2023/5/103165_0s.png)
Python开发毕设案例之桌面学生信息管理程序
2021-03-02 14:56:08
![](https://img.aspxhome.com/file/2023/2/76752_0s.png)
教你使用TensorFlow2识别验证码
2022-06-26 19:24:38
![](https://img.aspxhome.com/file/2023/3/92443_0s.jpg)
MYSQL5 下的兼容说明(my.ini my.conf)
2008-02-23 10:13:00
python将ip地址转换成整数的方法
2022-10-17 23:40:23
Python程序退出方式小结
2021-12-21 19:29:55
![](https://img.aspxhome.com/file/2023/6/79486_0s.jpg)
如何修改被表单引用的ASP页面?
2010-06-10 18:32:00
Python大数据之使用lxml库解析html网页文件示例
2022-05-10 11:06:53
![](https://img.aspxhome.com/file/2023/5/87705_0s.png)
巧妙使用python opencv库玩转视频帧率
2023-02-01 13:54:30
python调试神器PySnooper的使用
2021-08-28 23:25:49
Python实战之外星人入侵游戏示例代码
2023-12-23 08:18:18
![](https://img.aspxhome.com/file/2023/4/109954_0s.jpg)
MySQL安全性指南 (2)
2010-07-26 13:26:00
MIME Type 引出的两难困境
2011-06-14 09:45:41
Python Panda中索引和选择 series 的数据
2023-05-03 10:02:56
![](https://img.aspxhome.com/file/2023/5/77865_0s.png)
Python通过tkinter实现百度搜索的示例代码
2022-06-28 01:28:46
Django-Rest-Framework 权限管理源码浅析(小结)
2021-11-02 06:18:49
![](https://img.aspxhome.com/file/2023/9/117319_0s.png)
Python面向对象中类(class)的简单理解与用法分析
2021-01-05 00:07:37
对Python3使运行暂停的方法详解
2021-02-05 22:55:21
![](https://img.aspxhome.com/file/2023/8/82738_0s.jpg)
php中-> 、=>、::、$this->四种常见符号使用方法技巧
2023-05-30 07:46:24