[英]Unpacking List of Tuples of List(s)
我有一個元組列表,其中元組中的一個元素是一個列表。
example = [([0, 1, 2], 3, 4), ([5, 6, 7], 8, 9)]
我想最后得到一個元組列表
output = [(0, 1, 2, 3, 4), (5, 6, 7, 8, 9)]
這個問題似乎解決了元組的問題,但我擔心因為我的用例在內部列表中有更多的元素
[(a, b, c, d, e) for [a, b, c], d, e in example]
看起來很單調乏味。 有沒有更好的方法來寫這個?
元組可以與+
like列表連接。 所以,你可以這樣做:
>>> example = [([0, 1, 2], 3, 4), ([5, 6, 7], 8, 9)]
>>> [tuple(x[0]) + x[1:] for x in example]
[(0, 1, 2, 3, 4), (5, 6, 7, 8, 9)]
請注意,這適用於Python 2.x和3.x.
在Python3中你也可以這樣做:
[tuple(i+j) for i, *j in x]
如果你不想拼出輸入的每一部分
如果編寫函數是一個選項:
from itertools import chain
def to_iterable(x):
try:
return iter(x)
except TypeError:
return x,
example = [([0, 1, 2], 3, 4), ([5, 6, 7], 8, 9)]
output = [tuple(chain(*map(to_iterable, item))) for item in example]
這使:
print(output)
[(0, 1, 2, 3, 4), (5, 6, 7, 8, 9)]
它比其他解決方案更冗長,但無論內部元組中列表的位置或數量如何,它都具有工作的優勢。 根據您的要求,這可能是過度殺傷或一個好的解決方案。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.