[英]How can I find groups of consecutive items in a python list?
我有一个这样的排序列表[1,2,3,4,6,7,8,9,10,12,14]
我查找了不同的类似解决方案,但他们在我的案例中没有提供帮助
我希望这个列表输出像[ [1,4], [6,10], [12], [14] ]
所以基本上是一个包含序列开头和结尾的列表。 老实说看起来很容易,但我现在有点困惑。 任何帮助将不胜感激 !
您可以在https://pypi.org/project/more-itertools/上使用more_itertools.consecutive_groups 。
from more_itertools import consecutive_groups
#Get the groupings of consecutive items
li = [list(item) for item in consecutive_groups([1,2,3,4,6,7,8,9,10,12,14])]
#[[1, 2, 3, 4], [6, 7, 8, 9, 10], [12], [14]]
#Use the result to get range groupings
result = [ [item[0],item[-1]] if len(item) > 1 else [item[0]] for item in li]
print(result)
#[[1, 4], [6, 10], [12], [14]]
解决方案可能如下所示
def make_ranges(l: list):
prev = l[0]
start = l[1]
res = []
for v in l[1:]:
if v - 1 != prev:
if start == prev:
res.append([start])
else:
res.append([start, prev])
start = v
prev = v
if l[-1] - 1 == l[-2]:
res.append([start, l[-1])
return res
例如:
print(make_ranges(list(range(10)) + list(range(13, 20)) + [22]))
此代码将打印[[0, 9], [13, 19], [22]]
使用标准itertools
groupby
:
from itertools import groupby
lst = [1,2,3,4,6,7,8,9,10,12,14]
result = []
for k, g in groupby(enumerate(lst), lambda x: x[0] - x[1]):
g = list(map(lambda x: x[1], g))
if len(g) > 1:
result.append([g[0], g[-1]])
else:
result.append([g[0]])
print(result)
# [[1, 4], [6, 10], [12], [14]]
使用pandas
import pandas as pd
s = pd.Series([1,2,3,4,6,7,8,9,10,12,14])
s.groupby(s.diff().ne(1).cumsum()).apply(lambda x: [x.iloc[0], x.iloc[-1]] if len(x) >= 2 else [x.iloc[0]]).tolist()
输出
[[1, 4], [6, 10], [12], [14]]
使用numpy
import numpy as np
myarray = [1,2,3,4,6,7,8,9,10,12,14]
sequences = np.split(myarray, np.array(np.where(np.diff(myarray) > 1)[0]) + 1)
l = []
for s in sequences:
if len(s) > 1:
l.append((np.min(s), np.max(s)))
else:
l.append(s[0])
print(l)
输出:
[(1, 4), (6, 10), 12, 14]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.