解包列表元组列表

2024-03-29 00:31:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个元组列表,其中元组中的一个元素是一个列表。在

example = [([0, 1, 2], 3, 4), ([5, 6, 7], 8, 9)]

最后我只想得到一个元组的列表

^{pr2}$

这个question似乎解决了元组的问题,但我担心的是我的用例在内部列表和

[(a, b, c, d, e) for [a, b, c], d, e in example]

看起来很乏味。有没有更好的方法来写这个?在


Tags: 方法in元素列表forexample用例元组
3条回答

元组可以与+类似的列表连接。所以,你可以:

>>> 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)]

请注意,这在python2.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]

它给出了:

^{pr2}$

它比其他解决方案要复杂得多,但是它的优点是不管内部元组中列表的位置或数量如何都可以工作。根据您的需求,这可能是一个过激或好的解决方案。在

相关问题 更多 >