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

4 投票
3 回答
10908 浏览
提问于 2025-04-15 23:16

我想知道怎么检查我的列表中是否有一串连续的数字,比如:

如果我想找两个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

我不太明白你想要做什么,不过我准备了一个简单的脚本,虽然不太完美,但能满足你的需求。

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

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

这里有一个版本,它允许你指定要匹配的数字,并且在第一次替换后就停止。

撰写回答