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.
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.
To get every nth element in a list, a solution is to do mylist[::n].
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.
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.
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]
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