I want to write a succinct and elegant code for the following problem:
Assuming that I have a list of tuples:
[(x1,y1), (x2,y2), ....., (xn,yn)].
I want to create a list [y1, y2, ....,yn]
without using the loops.
Any help appreciated.
I want to write a succinct and elegant code for the following problem:
Assuming that I have a list of tuples:
[(x1,y1), (x2,y2), ....., (xn,yn)].
I want to create a list [y1, y2, ....,yn]
without using the loops.
Any help appreciated.
You can do this:
>>> x = [(1,2),(3,4),(5,6)]
>>> x2 = [k[1] for k in x]
>>> x2
[2, 4, 6]
The list comprehension does a loop internally, but you didn't have to type the words for
or while
. Is that what you're looking for?
mtrw has the right idea in standard Python. However, if you'd like to make the jump directly to numpy, I highly recommend it. It allows for all sort of indexing:
import numpy as np
x = np.array([(1,2),(3,4),(4,5)])
x[:,1]
Result:
array([2,4,6])
Edit: In addition to this simple indexing, you can loop over the arrays like any list, and has all the same properties plus more. Edit 2: vanilla -> standard