How to pick consecutive numbers from a list [duplicate]

北慕城南 提交于 2019-12-30 14:50:14

问题


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]

回答1:


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)



回答2:


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


来源:https://stackoverflow.com/questions/54520273/how-to-pick-consecutive-numbers-from-a-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!