Reputation: 29
I have this group of numbers:
a=[1,2,3,4,5,6]
and I have their indices grouped like this:
indices = [[0],[1,2],[3,4,5]]
I want to group the numbers in list 'a' in the way how their indices are grouped to get something like this:
b= [[1],[2,3],[4,5,6]]
Thanks for your help!
Upvotes: 2
Views: 53
Reputation: 17911
You can use the function 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]]
Upvotes: 0
Reputation: 2980
This should do the trick:
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]
Upvotes: 4