我有清单
my_list= [33,29,33,87,83,138,141,145,191,191,191]
现在我有另一个清单
split_list = [2,4,7]
现在我需要使用split_list中的值作为my_list的位置值来分隔my_list值,
在这个link中,他们使用scala将每个列表中的4个元素分组到列表中,就像明智一样,我想将split_list中的数字用作分组因子
像这样answer_list = [(33,29,33),(87,83),(138,141,145),(191,191,191)]
答案 0 :(得分:3)
您可以通过稍微调整split_list
:
>>> my_list= [33,29,33,87,83,138,141,145,191,191,191]
>>> split_list = [2,4,7]
>>> split_list = [-1] + split_list + [len(my_list)]
>>> [tuple(my_list[split_list[i]+1:split_list[i+1]+1]) for i in range(len(split_list)-1)]
[(33, 29, 33), (87, 83), (138, 141, 145), (191, 191, 191)]
如果索引是切片发生之前的项的索引,那么您可以使用更好的代码:
>>> my_list= [33,29,33,87,83,138,141,145,191,191,191]
>>> split_list = [2,4,7]
>>> split_list = [i + 1 for i in split_list] # To change the list to [3,5,8]
>>> split_list = [None] + split_list + [None]
>>> [tuple(my_list[split_list[i]:split_list[i+1]]) for i in range(len(split_list)-1)]
[(33, 29, 33), (87, 83), (138, 141, 145), (191, 191, 191)]
答案 1 :(得分:0)
工作,虽然不是很优雅:
first = 0
answer_list = []
for last in split_list:
answer_list.append(my_list[first:last+1])
first = last+1
answer_list.append(my_list[first:])
答案 2 :(得分:0)
您可以使用使用列表切片:
my_list= [33,29,33,87,83,138,141,145,191,191,191]
split_list= [2,4,7]
split_list.append(len(my_list)-1)
answer_list = []
prev = 0
for i in split_list :
answer_list.append(tuple(my_list[prev:i+1]))
prev = i+1
print(answer_list)
输出:[(33, 29, 33), (87, 83), (138, 141, 145), (191, 191, 191)]