可能有很多方法可以做到这一点.这是基于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)