Python在列表中查找n个连续数字

时间:2010-05-28 07:07:55

标签: python

我想知道如何查找列表中的连续数字是否存在一定数量,例如

例如,如果我正在寻找两个1,那么:

list = [1, 1, 1, 4, 6] #original list
list = ["true", "true", 1, 4, 6] #after my function has been through the list.

如果我正在寻找三个1,那么:

list = [1, 1, 1, 4, 6] #original list
list = ["true", "true", "true", 4, 6] #after my function has been through the list.

我试过了:

list = [1, 1, 2, 1]

1,1,1 in list #typed into shell, returns "(1, 1, True)"

我将非常感谢任何帮助,我主要想了解最新情况,以及如何检查列表中的下一个元素是否与第一个x数量相同。

3 个答案:

答案 0 :(得分:10)

分配给list是一个坏主意。使用其他名称。

要查找最大数量的连续相等值,您可以使用itertools.groupby

>>> import itertools
>>> l = [1, 1, 1, 4, 6]
>>> max(len(list(v)) for g,v in itertools.groupby(l)) 
3

仅搜索连续的1:

>>> max(len(list(v)) for g,v in itertools.groupby(l, lambda x: x == 1) if g) 
3

答案 1 :(得分:1)

>>> def find_repeats(L, num_repeats):
...     idx = 0
...     while idx < len(L):
...         if [L[idx]]*num_repeats == L[idx:idx+num_repeats]:
...             L[idx:idx+num_repeats] = [True]*num_repeats
...             idx += num_repeats
...         else:
...             idx += 1
...     return L
... 
>>> L=[1,1,1,4,6]
>>> print find_repeats(L, 2)
[True, True, 1, 4, 6]
>>> L=[1,1,1,4,6]
>>> print find_repeats(L, 3)
[True, True, True, 4, 6]
>>> 

这是一个版本,可让您指定应匹配的号码,并在第一次更换后停止

>>> def find_repeats(L, required_number, num_repeats, stop_after_match=False):
...     idx = 0
...     while idx < len(L):
...         if [required_number]*num_repeats == L[idx:idx+num_repeats]:
...             L[idx:idx+num_repeats] = [True]*num_repeats
...             idx += num_repeats
...             if stop_after_match:
...                 break
...         else:
...             idx += 1
...     return L
... 
>>> L=[1,1,1,4,6]
>>> print find_repeats(L, 1, 2)
[True, True, 1, 4, 6]
>>> L=[1,1,1,4,6]
>>> print find_repeats(L, 1, 3)
[True, True, True, 4, 6]
>>> L=[1,1,1,4,4,4,6]
>>> print find_repeats(L, 1, 3)
[True, True, True, 4, 4, 4, 6]
>>> L=[1,1,1,4,4,4,6]
>>> print find_repeats(L, 4, 3)
[1, 1, 1, True, True, True, 6]

答案 2 :(得分:0)

我无法理解你想做什么,但我准备了一个快速而不是很好的剧本,但它可以满足你的需要。

def repeated(num, lyst):
 # the 'out' list will contain the array you are looking for
 out = []
 # go through the list (notice that you go until "one before
 # the end" because you peek one forward)
 for k in range(len(lyst)-1):
  if lyst[k] == lyst[k+1] == num:
    # if the numbers are equal, add True (as a bool, but you could
    # also pass the actual string "True", as you have it in your question)
    out.append(True)
  else:
   # if they are not the same, add the number itself
    out.append(lyst[k])
 # check the last element: if it is true, we are done (because it was the same as the
 # last one), if not, then we add the last number to the list (because it was not the
 # same)
 if out[-1] != True:
  out.append(lyst[-1])
 # return the list  
 return out

使用它像:

print repeated(1, [1, 1, 1, 4, 6])