如何从列表中选择连续的数字[复制]

问题描述 投票:0回答:2

这个问题已经在这里有一个答案:

Ive得到了其实际持有指数另一个列表清单。因此,我想从这个列表中选择出来的连续号码

index_list=[3,4,8,9,35,36,37]

从我想要的输出作为

[3:4], [8:9], [35:37]

---------------------声明:---------------------

我有字的另一主列表,其中有80个字。

  master_list=['was,'it','to,'go,'I'.........] 

因此,连续的指数将帮助我从master_list挑选出需要的话作为

master_list[3:4], master_list[8:9], master_list[35:37]
python python-3.x slice
2个回答
1
投票

有可能很多方法可以做到这一点。这里有一个基于reduce()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']
%

请注意,这会将第二个号码在片中在习惯Python的方式,它是一个超出了我们想要的东西。如果是真的,你想要什么,然后修改与+ 1此元素的最后一个项目:

(array[0], array[-1] + 1)

1
投票

使用多通用的方法:

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

更新:

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]]
© www.soinside.com 2019 - 2024. All rights reserved.