如何找到列表中彼此相邻的最大1s(或任何我想要的元素)?
l = [2, 1, 2, 1, 1, 1, 1, 2, 2, 2, 1, 2, 7, 1, 1, 1]
在这种情况下,我需要一个返回4的函数。
谢谢。
答案 0 :(得分:1)
groupby()函数可用于此:
import itertools
l = [2, 1, 2, 1, 1, 1, 1, 2, 2, 2, 1, 2, 7, 1, 1, 1]
print(max([len(list(g))*k for k, g in itertools.groupby(l, lambda x: x == 1)]))
答案 1 :(得分:0)
手动:
def makeMyHomework(li):
'''reads a list of int's and looks for the logest run of one int'''
curVal = None
curCount = 0
maxVal = None
maxCount = -1
for n in l:
if curVal == None:
curVal = n
if curVal == n:
curCount +=1
if curVal != n:
if curCount > maxCount: # check if current run > max so far
maxVal = curVal # store new max value
maxCount = curCount # store new max count
curVal = n # init the act ones
curCount = 1 # -"-
# print (n, ":", curVal, curCount, maxVal,maxCount)
# edge case - the max list is the last run
if curCount > maxCount:
maxVal = curVal
maxCount = curCount
return (maxVal, maxCount) # tuple of (value, number of occurences)
l = [2, 1, 2, 1, 1, 1, 1, 2, 2, 2, 1, 2, 7, 1, 1, 1,2,2,2,2,2]
print(makeMyHomework(l))