Reputation: 115
As last part of a bigger project here is what I am trying to solve:
I have a list of lists of which I need to extract exactlty one element based on the value of a second list.
a = [[6,2,3,9], [10,19,14,11], [27,28,21,24]]
b = [0,2,2]
The values in b
indicate the positions of the elements in the sublists. Also, the index in b
is the true for the index of elements in list a
.
The result I am looking for is:
c = [6, 14, 21]
I have tried many versions of this:
c = [i[j] for i in a for j in b]
But as a result I get a list over all emements of all lists looking like this:
c = [6, 3, 3, 10, 14, 14, 27, 21, 21]
Upvotes: 4
Views: 862
Reputation: 71570
Or:
[v[b[i]] for i,v in enumerate(a)]
Example:
>>> a = [[6,2,3,9], [10,19,14,11], [27,28,21,24]]
>>> b = [0,2,2]
>>> [v[b[i]] for i,v in enumerate(a)]
[6, 14, 21]
>>>
Upvotes: 1
Reputation: 158
You can try the following.
a = [[6,2,3,9], [10,19,14,11], [27,28,21,24]]
b = [0,2,2]
c = []
for i in range(0, len(b)):
c.append(a[i][b[i]])
print (c)
Upvotes: -1
Reputation: 73450
By using nested loops, you are combining every element from a
with every element from b
. What you want is pair-wise iteration, using zip
:
c = [x[y] for x, y in zip(a, b)]
# [6, 14, 21]
This is roughly equivalent to:
c = [a[i][b[i]] for i in range(min(len(a), len(b)))]
Upvotes: 3