Using list comprehension I have created a list of tuples which looks like
temp = [(1, 0, 1, 0, 2), (1, 0, 1, 0, 5), (1, 0, 2, 0, 2), (1, 0, 2, 0, 5)]
I could also create a list of lists if that works easier.
Either way, I would now like to get an array, or a 2D list, from the data. Something where I can easily access the value of the first element in each tuple in the above using slicing, something like
first_elements = temp[:,0]
Use numpy for that type of indexing:
import numpy as np
temp = [(1, 0, 1, 0, 2), (1, 0, 1, 0, 5), (1, 0, 2, 0, 2), (1, 0, 2, 0, 5)]
a = np.array(temp)
a[:, 0]
returns
array([1, 1, 1, 1])
Note: all of your inner lists must be of the same size at for this to work. Otherwise the array constructor will return an array of Python lists.
You can use zip
and next
to get what you want:
temp = [(1, 0, 1, 0, 2), (1, 0, 1, 0, 5), (1, 0, 2, 0, 2), (1, 0, 2, 0, 5)]
print(next(zip(*temp)))
Returns:
(1, 1, 1, 1)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With