4

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]
michael_heath
  • 5,262
  • 2
  • 12
  • 22
AvePazuzu
  • 95
  • 7

4 Answers4

3

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)))]
user2390182
  • 72,016
  • 6
  • 67
  • 89
  • 1
    Thanks!!! I did not use zip before in this way. But this seems to be really a fast and simple way to do this. – AvePazuzu Oct 16 '18 at 06:54
1

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]
>>> 
U13-Forward
  • 69,221
  • 14
  • 89
  • 114
-1

Try this:

c = [a[i][b[i]] for i in xrange(len(b))]
Prem
  • 85
  • 3
  • Or we can use enumerate(b) – nghiaht Oct 16 '18 at 06:52
  • this is just so un-pythonic – Jean-François Fabre Oct 16 '18 at 07:10
  • 2
    While this might answer the authors question, it lacks some explaining words and links to documentation. Raw code snippets are not very helpful without some phrases around it. You may also find [how to write a good answer](https://stackoverflow.com/help/how-to-answer) very helpful. Please edit your answer. – hellow Oct 16 '18 at 07:37
-1

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)
Shweta Valunj
  • 148
  • 1
  • 11