Flattening a list of tuples [duplicate]

﹥>﹥吖頭↗ 提交于 2019-12-12 04:43:49

问题


How can I loop through all the elements in a list of tuples, into an empty list?

For example:

tup_Before = [(69592, 69582), (69582, 69518), (69518, 69532), (69532, 69525)]

tup_After = [69592, 69582, 69582, 69518, 69518, 69532, 69532, 69525]

回答1:


A list comprehension:

tup_after = [v for t in tup_Before for v in t]

or use itertools.chain.from_iterable():

from itertools import chain
tup_after = list(chain.from_iterable(tup_Before))

Demo:

>>> tup_Before = [(69592, 69582), (69582, 69518), (69518, 69532), (69532, 69525)]
>>> [v for t in tup_Before for v in t]
[69592, 69582, 69582, 69518, 69518, 69532, 69532, 69525]
>>> from itertools import chain
>>> list(chain.from_iterable(tup_Before))
[69592, 69582, 69582, 69518, 69518, 69532, 69532, 69525]



回答2:


also, the least clear answer:

[l for l in l for l in l]

where l is your list name




回答3:


You can try using itertools.chain() and unpacking with *:

import itertools

new_tup = list(itertools.chain(*tup_before))

Demo:

>>> print new_tup
[69592, 69582, 69582, 69518, 69518, 69532, 69532, 69525]


来源:https://stackoverflow.com/questions/22643557/flattening-a-list-of-tuples

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