展平元组列表 [英] Flattening a list of tuples
本文介绍了展平元组列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何将元组列表中的所有元素循环到一个空列表中?
How can I loop through all the elements in a list of tuples, into an empty list?
例如:
tup_Before = [(69592, 69582), (69582, 69518), (69518, 69532), (69532, 69525)]
tup_After = [69592, 69582, 69582, 69518, 69518, 69532, 69532, 69525]
推荐答案
列表理解:
tup_after = [v for t in tup_Before for v in t]
或使用itertools.chain.from_iterable()
:
from itertools import chain
tup_after = list(chain.from_iterable(tup_Before))
演示:
>>> 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]
这篇关于展平元组列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文