Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get every first element in 2 dimensional list

I have a list like this:

a = [[4.0, 4, 4.0], [3.0, 3, 3.6], [3.5, 6, 4.8]]

I want an outcome like this (EVERY first element in the list):

4.0, 3.0, 3.5

I tried a[::1][0], but it doesn't work

like image 319
CodingBeginner Avatar asked May 05 '15 20:05

CodingBeginner


People also ask

How do you extract the first element of a list?

To extract only first element from a list, we can use sapply function and access the first element with double square brackets. For example, if we have a list called LIST that contains 5 elements each containing 20 elements then the first sub-element can be extracted by using the command sapply(LIST,"[[",1).


3 Answers

You can get the index [0] from each element in a list comprehension

>>> [i[0] for i in a] [4.0, 3.0, 3.5] 
like image 139
Cory Kramer Avatar answered Sep 21 '22 06:09

Cory Kramer


Use zip:

columns = zip(*rows) #transpose rows to columns
print columns[0] #print the first column
#you can also do more with the columns
print columns[1] # or print the second column
columns.append([7,7,7]) #add a new column to the end
backToRows = zip(*columns) # now we are back to rows with a new column
print backToRows

You can also use numpy:

a = numpy.array(a)
print a[:,0]

Edit: zip object is not subscriptable. It need to be converted to list to access as list:

column = list(zip(*row))
like image 42
Joran Beasley Avatar answered Sep 24 '22 06:09

Joran Beasley


You can get it like

[ x[0] for x in a]

which will return a list of the first element of each list in a

like image 29
Eric Renouf Avatar answered Sep 20 '22 06:09

Eric Renouf