从列表列表中识别连续整数

时间:2021-02-14 08:46:44

标签: python python-3.x list

我有以下列表,我想从所有列表中获取连续的整数。

list = [[3, 10, 15, 88],
[4, 11, 30],
[1, 6, 12, 50, 74]]

它应该返回 [10, 11, 12]

如果有多个连续的列表像

list = [[3, 10, 15, 88],
[4, 11, 30],
[5, 6, 12, 50, 74]]

它应该同时返回 [3,4,5][10,11,12]

我想知道最有效的解决方案。谢谢。

4 个答案:

答案 0 :(得分:1)

l = [[3, 10, 15, 88], 
    [4, 11, 30], 
    [5, 6, 12, 50, 74]]  

result = [[elem-1,elem,elem+1] for elem in l[1] if (elem+1) in l[2] and (elem-1) in l[0] ]

[[3, 4, 5], [10, 11, 12]]

for elem in l[1] :我们将遍历中间列表并检查是否elem+1在下一个列表中,elem-1在前一个列表中

答案 1 :(得分:0)

在一行中使用 product 试试这个:

from itertools import product  
                                                                                                                                                                                                                                               
l = [[3, 10, 15, 88], 
    [4, 11, 30], 
    [5, 6, 12, 50, 74]]  

result = [[i,j,k] for i,j,k in product(*l) if k==j+1 and j==i+1] 

结果将是:

In [7]: result                                                                                                                                                                                                                                                                            
Out[7]: [[3, 4, 5], [10, 11, 12]]
<块引用>

注意:不要使用 list 作为变量名。它是在 python 中预定义的,你将覆盖它的主要功能。

答案 2 :(得分:0)

您可以简单地执行此操作以获得所需的答案

from operator import itemgetter
data = [ 1,4,5,6,10,15,16,17,18,22,25,26,27,28]
for k, g in groupby(enumerate(data), lambda (i, x): i-x):
   print map(itemgetter(1), g)

Result:
[1]
[4, 5, 6]
[10]
[15, 16, 17, 18]
[22]
[25, 26, 27, 28]

答案 3 :(得分:0)

简单的推理

l = [[3, 10, 15, 88],
[4, 11, 30],
[5, 6, 12, 50, 74]]

l2 = [(index,j) for index,i in enumerate(l) for j in i] # flattening the list
l2 = sorted(l2, key= lambda x: x[1]) # sorting the list
# the sorted list has the below structure (sublist_number, item)

output = []
current_group = []
temp = []

for i in l2:
    if(len(temp) == 0):
        temp.append(i[1])
        current_group.append(i[0])
    else:
        if(i[1] - temp[-1] != 1): # that means not consecutive
            if(len(temp) == 3):
                output.append(temp.copy())
            temp.clear()
            current_group.clear()
            temp.append(i[1])
            current_group.append(i[0])
        else:
            if(i[0] not in current_group):
                temp.append(i[1])
                current_group.append(i[0])

print(output)
[[3, 4, 5], [10, 11, 12]]