我有这组数字:
a=[1,2,3,4,5,6]
我将他们的索引分组如下:
indices = [[0],[1,2],[3,4,5]]
我想按照其索引的分组方式将列表“ a”中的数字分组,以获得类似这样的结果:
b= [[1],[2,3],[4,5,6]]
感谢您的帮助!
答案 0 :(得分:4)
这应该可以解决问题:
a = [1,2,3,4,5,6]
indices = [[0],[1,2],[3,4,5]]
result = [[a[index] for index in index_list] for index_list in indices]
答案 1 :(得分:0)
您可以使用函数itemgetter()
:
from operator import itemgetter
a = [1,2,3,4,5,6]
indices = [[0],[1,2],[3,4,5]]
[list(itemgetter(*i)(a)) if len(i) > 1 else [itemgetter(*i)(a)]
for i in indices]
# [[1], [2, 3], [4, 5, 6]]