Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the nth element from the inner list of a list of lists in Python [duplicate]

Tags:

Possible Duplicate:
First items in inner list efficiently as possible

Lets say I have:

a = [ [1,2], [2,9], [3,7] ] 

I want to retrieve the first element of each of the inner lists:

b = [1,2,3] 

Without having to do this (my current hack):

for inner in a:     b.append(inner[0]) 

I'm sure there's a one liner for it but I don't really know what i'm looking for.

like image 447
jsj Avatar asked Nov 02 '12 02:11

jsj


People also ask

How do you extract an element from a nested list in Python?

Approach #2 : Using zip and unpacking(*) operator This method uses zip with * or unpacking operator which passes all the items inside the 'lst' as arguments to zip function. Thus, all the first element will become the first tuple of the zipped list. Returning the 0th element will thus, solve the purpose.

How do you find the nth element of a list in Python?

To get every nth element in a list, a solution is to do mylist[::n].

How do I separate a list from a list in Python?

The split() method of the string class is fairly straightforward. It splits the string, given a delimiter, and returns a list consisting of the elements split out from the string. By default, the delimiter is set to a whitespace - so if you omit the delimiter argument, your string will be split on each whitespace.

How do you create a list inside a list in Python?

Using append() function to create a list of lists in Python. What append() function does is that it combines all the lists as elements into one list. It adds a list at the end of the list.


1 Answers

Simply change your list comp to be:

b = [el[0] for el in a] 

Or:

from operator import itemgetter b = map(itemgetter(0), a) 

Or, if you're dealing with "proper arrays":

import numpy as np a = [ [1,2], [2,9], [3,7] ] na = np.array(a) print na[:,0] # array([1, 2, 3]) 

And zip:

print zip(*a)[0] 
like image 179
Jon Clements Avatar answered Oct 06 '22 06:10

Jon Clements