简体   繁体   中英

How to flatten a list of tuples into a pythonic list

Given the following list of tuples:

INPUT = [(1,2),(1,),(1,2,3)]

How would I flatten it into a list?

OUTPUT ==> [1,2,1,1,2,3]

Is there a one-liner to do the above?

Similar: Flatten list of Tuples in Python

You could use a list comprehension :

>>> INPUT = [(1,2),(1,),(1,2,3)]
>>> [y for x in INPUT for y in x]
[1, 2, 1, 1, 2, 3]
>>>

itertools.chain.from_iterable is also used a lot in cases like this:

>>> from itertools import chain
>>> INPUT = [(1,2),(1,),(1,2,3)]
>>> list(chain.from_iterable(INPUT))
[1, 2, 1, 1, 2, 3]
>>>

That's not exactly a one-liner though.

>>> INPUT = [(1,2),(1,),(1,2,3)]
>>> import itertools
>>> list(itertools.chain.from_iterable(INPUT))
[1, 2, 1, 1, 2, 3]

you can use sum which adds up all of the elements if it's a list of list (singly-nested).

sum([(1,2),(1,),(1,2,3)], ())

or convert to list:

list(sum([(1,2),(1,),(1,2,3)], ()))

Adding up lists works in python.

Note : This is very inefficient and some say unreadable.

>>> INPUT = [(1,2),(1,),(1,2,3)]  
>>> import operator as op
>>> reduce(op.add, map(list, INPUT))
[1, 2, 1, 1, 2, 3]

Not in one line but in two:

>>> out = []
>>> map(out.extend, INPUT)
... [None, None, None]
>>> print out
... [1, 2, 1, 1, 2, 3]

Declare a list object and use extend.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM