This question already has an answer here:
-
Identify groups of continuous numbers in a list
12 answers
Ive got a list which actually hold indices for another list. Hence I want to pick out the consecutive numbers from this list
index_list=[3,4,8,9,35,36,37]
from which i want the output as
[3:4], [8:9], [35:37]
---------------------MOTIVE:---------------------
I have another master list of words, which has 80 words.
master_list=['was,'it','to,'go,'I'.........]
Thus the consecutive indices will help me pick out the required words from master_list as
master_list[3:4], master_list[8:9], master_list[35:37]
There are likely lots of ways to do this. Here's one based on reduce()
and islice()
:
from functools import reduce
from itertools import islice
qw = [3, 4, 8, 9, 12, 13, 14]
master_list = ['Thus', 'the', 'consecutive', 'indices', 'will', 'help', 'me', 'pick', 'out', 'the', 'required', 'words', 'from', 'master_list', 'as']
def divide(value, element):
if not value[-1] or element - value[-1][-1] == 1:
value[-1].append(element)
else:
value.append([element])
return value
slices = [(array[0], array[-1]) for array in reduce(divide, qw, [[]])]
print(slices)
for sliced in slices:
print(list(islice(master_list, *sliced)))
OUTPUT
% python3 test.py
[(3, 4), (8, 9), (12, 14)]
['indices']
['out']
['from', 'master_list']
%
Note that this treats the second number in the slice in the customary Python manner in that it's one beyond what we want. If it's really the last item of what you want then modify this element with a + 1
:
(array[0], array[-1] + 1)
Using much generalized way:
i = 0
final_list = []
flag = True
while flag:
temp_list = [index_list[i]]
while (i < len(index_list)-1) and (index_list[i+1] - index_list[i]==1):
i+=1
temp_list.append(index_list[i])
final_list.append(temp_list)
i+=1
if i >= len(index_list):
flag=False
print(final_list)
input : [3,4,8,9,35,36,37]
ouptut : [[3, 4], [8, 9], [35, 37]]
input : [1,3,5,7,9]
output : [[1, 1], [3, 3], [5, 5], [7, 7], [9, 9]]
Update:
new_list = []
for i, j in final_list:
new_list.append(list(range(i,j+1)))
print(new_list)
input: [3, 4, 5, 16, 17, 31, 32, 33, 34]
output : [[3, 4, 5], [16, 17], [31, 32, 33, 34]]