【问题标题】:Unpacking List of Tuples of List(s)列表元组的拆包列表
【发布时间】:2015-08-02 01:01:55
【问题描述】:

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

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

我只想得到一个元组列表

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

这个question 似乎解决了元组的问题,但我担心我的用例在内部列表中有更多元素,并且

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

看起来很乏味。有没有更好的写法?

【问题讨论】:

  • 你的所有元组都完全匹配([a, b, c], d, e) 模式吗?
  • 是的。我的实际列表有 100 个元素,但 100 个元素是统一的,并且外部总是有 2 个元素。
  • 如果列表中的所有元组都匹配 ([a, b, c], d, e) 的模式,那么您的代码是 Pythonic 并且看起来并不乏味。
  • 列表在元组中的位置可以改变还是固定?
  • 元组中的列表总是第零​​个

标签: python list tuples list-comprehension


【解决方案1】:

在 Python3 中你也可以这样做:

[tuple(i+j) for i, *j in x]

如果您不想拼写输入的每个部分

【讨论】:

  • 我喜欢它!想解释一下像我这样仍然坚持使用 Python 2.x 的可怜人到底发生了什么?
  • SyntaxError: invalid syntax on the *j 适用于 Python2.x。
【解决方案2】:

如果编写函数是一种选择:

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

它比其他解决方案更冗长,但无论内部元组中列表的位置或数量如何,它都具有工作的整洁优势。根据您的要求,这可能是矫枉过正或一个好的解决方案。

【讨论】:

    【解决方案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)]
    

    请注意,这适用于 Python 2.x 和 3.x。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-04-27
      • 2019-10-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-28
      • 2012-10-31
      相关资源
      最近更新 更多