繁体   English   中英

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

[英]Python finding n consecutive numbers in a list

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

例如,如果我正在寻找两个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量相同。

分配给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
>>> 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]

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

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])

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM