使用列表推导:
my_list = [ 5, 8, 3, 0, 0, 1, 3, 4, 8, 13, 0, 0, 0, 0, 21, 34, 25, 91, 61, 0, 0,]
my_tups = [(5,9), (14,18)]
new_list = [my_list[i:j] for i,j in my_tups]
在您发表评论后:
my_list = [ 5, 8, 3, 0, 0, 1, 3, 4, 8, 13, 0, 0, 0, 0, 21, 34, 25, 91, 61, 0, 0]
my_tups = [(5,9), (14,18)]
new_list = [0 for i in my_list] # Create a list filled with zeros
for i,j in my_tups:
new_list[i:j] = my_list[i:j] # Replace items with items from my_list using the indexes from my_tups
输出:
>>> new_list
[0, 0, 0, 0, 0, 1, 3, 4, 8, 0, 0, 0, 0, 0, 21, 34, 25, 91, 0, 0, 0]