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]
有帮助吗?

解决方案

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]

其他提示

also, the least clear answer:

[l for l in l for l in l]

where l is your list name

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]
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top