manipulating lists to find different variables

The following is the first line from my list l:

 [0.0, 753.128, 990.43, 686.832, 366.922, -93.454, 1.0]

This is the result of:

 print l[0]

I want to take all the first element from all such *lines of my list and assign them to another list. How can I do it in python?

Answers


Using a list comprehension:

lists = [[1,2,3], [4,5,6]]
[ l[0] for l in lists ]

That would do it. Nicer is to use map: you map a list of lists to a list of their heads:

map( lambda l: l[0], lists )

If performance is important, you may want to create an iterator over the heads of your lists:

heads = itertools.imap( lambda l: l[0], enumerate(lists))

for head in heads:
   print head 

Basic list comprehension:

another_list = [sublist[0] for sublist in l]

Try this:

a = [[1,2,3], ['a','b','c'], [True, False]]

first_elements = [e[0] for e in a]

print first_elements

>>> [1, 'a', True]

Something like this?

>>> a = [1, 2, 3, 4]
>>> b = [5,6,7,8]
>>> ab = [a, b]
>>> map (lambda x : x[0], ab)
[1, 5]

newlist=[]
for l in lst:
    newlist.append(l[0])

Need Your Help

Mongodb indexing for aggregates

mongodb aggregation-framework

I'm using the following aggregate and wanted to see what would be the recommended indexes for this:

How do I adjust the opacity of a field when disabled in Java Swing

java swing opacity jtextfield

I have a program that when started disables fields so that the user cant change parameters. However the opacity changes so much that the writing then is not as clear as I would like. I set the font...