Given a list of Tuples, return a new list of the first values of the tuples
I have a list of tuples and I want a new list consisting of the first values of the tuples.
those. if the list is:
[(1.5), (4.10), (100.3), (4.8)]
I want to create the following list:
[1,4,100,4]
The following code works:
a = [(1,5),(4,10),(100,3),(4,8)] l = [] for i in range(len(a)): l.append(a[i][0])
But it seems like there should be a better way, for example:
l = itertools.chain(for i in range(len(a)) a[i][0]) #This won't work
+3
Alexander
source
to share
5 answers
How about a list comprehension:
l=[(1,5),(4,10),(100,3),(4,8)]
print [x[0] for x in l]
This will give you
[1, 4, 100, 4]
on request :)
+6
hochl
source
to share
I usually used a list comprehension:
>>> a = [(1,5),(4,10),(100,3),(4,8)]
>>> [x for x, y in a]
[1, 4, 100, 4]
+7
Sven Marnach
source
to share
If you don't want to understand the list, you can try this:
x = [(1,5),(4,10),(100,3),(4,8)]
first_vals = list(zip(*x)[0])
Result:
>>> first_vals
[1, 4, 100, 4]
+3
Akavall
source
to share
Try the following:
>>> a = [(1,5),(4,10),(100,3),(4,8)]
>>> [b[0] for b in a]
[1, 4, 100, 4]
+2
Nolen Royalty
source
to share
What about:
>>> map(lambda e: e[0], (e for e in a))
[1, 4, 100, 4]
+1
modocache
source
to share