Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting a list of tuples to an array or other structure that allows easy slicing

Tags:

python

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]
like image 298
jlt199 Avatar asked Feb 15 '18 15:02

jlt199


2 Answers

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.

like image 130
Alex Avatar answered Oct 03 '22 20:10

Alex


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)
like image 44
MooingRawr Avatar answered Oct 03 '22 21:10

MooingRawr