Creating a Python list from a list of tuples -


if have, example, list of tuples such as

a = [(1,2)] * 4 

how create list of first element of each tuple? is, [1, 1, 1, 1].

use list comprehension:

>>> = [(1,2)] * 4 >>> [t[0] t in a] [1, 1, 1, 1] 

you can unpack tuple:

>>> [first first,second in a] [1, 1, 1, 1] 

if want fancy, combine map , operator.itemgetter. in python 3, you'll have wrap construct in list list instead of iterable:

>>> import operator >>> map(operator.itemgetter(0), a) <map object @ 0x7f3971029290> >>> list(map(operator.itemgetter(0), a)) [1, 1, 1, 1] 

Comments

Popular posts from this blog

c# - SVN Error : "svnadmin: E205000: Too many arguments" -

c++ - Using OpenSSL in a multi-threaded application -

All overlapping substrings matching a java regex -