How to flatten a list of tuples into a pythonic list

筅森魡賤 提交于 2019-12-17 19:00:43

问题


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


回答1:


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.




回答2:


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



回答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.




回答4:


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



回答5:


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.



来源:https://stackoverflow.com/questions/27454390/how-to-flatten-a-list-of-tuples-into-a-pythonic-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!