python中计算一个列表中连续相同的元素个数方法
最简单的例子:
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
相关推荐
坚持是一种品质 2020-11-16
zhaobig 2020-11-16
文山羊 2020-10-31
kikaylee 2020-10-31
oXiaoChong 2020-10-30
PYTandFA 2020-09-15
CloudStrife0 2020-08-23
hang0 2020-08-16
lzujiangge 2020-08-16
RocNg 2020-08-15
xiesheng 2020-08-06
Tristahong 2020-08-05
georgeandgeorge 2020-08-03
elizabethxxy 2020-07-27
flycony 2020-07-05
柠檬班 2020-07-04
magicandy 2020-07-04
fanhuasijin 2020-06-27