如何循環遍歷元組列表中的所有元素到空列表中?壓扁元組列表
例如:
tup_Before = [(69592, 69582), (69582, 69518), (69518, 69532), (69532, 69525)]
tup_After = [69592, 69582, 69582, 69518, 69518, 69532, 69532, 69525]
如何循環遍歷元組列表中的所有元素到空列表中?壓扁元組列表
例如:
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]
還可以,至少明確的答案:
[l for l in l for l in l]
其中l
是您可以嘗試使用itertools.chain()
和拆包與*
列表名稱
:
import itertools
new_tup = list(itertools.chain(*tup_before))
演示:
>>> print new_tup
[69592, 69582, 69582, 69518, 69518, 69532, 69532, 69525]
一個簡單的reduce:'list(reduce(lambda x,y:x + y,tup_Before))'(lambda可以替換爲'operator .__ add__'以提高可讀性) – njzk2