【问题标题】:List comprehension to append an element to a tuple [duplicate]将元素附加到元组的列表理解[重复]
【发布时间】:2021-07-19 16:19:05
【问题描述】:

我有一个 numpy 数组

arr = np.array([
        [1, (10, 20, 30, 40)],
        [2, (10, 20, 30, 40)],
        [5, (11, 22, 33, 44)]
      ])

我想知道有没有办法可以得到:

ans = [
        [1, 10, 20, 30, 40],
        [2, 10, 20, 30, 40],
        [5, 11, 22, 33, 44]
      ]

在 python 中使用列表推导。

我试过了:

ans = [list(row[1]).append(row[0]) for row in arr]

但得到 [None, None, None] 作为输出

【问题讨论】:

  • 这不是一个 numpy 数组,所以你的问题没有实际意义。请提供与您的散文相匹​​配的代码。
  • [[first, *rest] for first, rest in arr]
  • append 会将125 放在各个列表的末尾,而不是放在开头。

标签: python arrays numpy


【解决方案1】:

append 返回None,而不是附加到的列表。 (另外,append 无论如何都会将项目插入错误的末尾。)

ans = [[x, *y] for x, y in arr]

【讨论】:

    猜你喜欢
    • 2017-04-16
    • 2017-11-28
    • 1970-01-01
    • 2019-06-23
    • 2020-12-11
    • 1970-01-01
    • 1970-01-01
    • 2011-03-17
    相关资源
    最近更新 更多