【问题标题】:How can I convert numpy ndarray to a list of tuples efficiently?如何有效地将 numpy ndarray 转换为元组列表?
【发布时间】:2019-03-25 11:33:06
【问题描述】:

这是我得到的 numpy.ndarray:

a=[[[ 0.01, 0.02 ]], [[ 0.03, 0.04 ]]]

我希望它转换为

a = [(0.01, 0.02), (0.03, 0.04)]

目前我只使用以下for 循环,但我不确定它是否足够高效:

b = []
for point in a:
   b.append((point[0][0], point[0][1]))
print(b)

我找到了一些 a similar question,但没有元组,所以建议的 ravel().tolist() 方法在这里对我不起作用。

【问题讨论】:

  • 你为什么要使用 lsit?
  • 附言。您不能在列表中附加 2 个元素
  • @DirtyBit 抱歉,刚刚编辑了问题。

标签: python numpy


【解决方案1】:
# initial declaration
>>> a = np.array([[[ 0.01, 0.02 ]], [[ 0.03, 0.04 ]]])
>>> a
array([[[0.01, 0.02]],
       [[0.03, 0.04]]])

# check the shape
>>> a.shape
(2L, 1L, 2L)

# use resize() to change the shape (remove the 1L middle layer)
>>> a.resize((2, 2))
>>> a
array([[0.01, 0.02],
       [0.03, 0.04]])

# faster than a list comprehension (for large arrays)
# because numpy's backend is written in C

# if you need a vanilla Python list of tuples:
>>> list(map(tuple, a))
[(0.01, 0.02), (0.03, 0.04)]

# alternative one-liner:
>>> list(map(tuple, a.reshape((2, 2))))
...

【讨论】:

  • 你有什么理由把2L放在那里?在 Python 3 中,所有整数都是长整数,所以我建议删除那些 Ls,以免让新的 Python 程序员认为这是“好风格”甚至“必需”。
  • @NOhs 我这样做是为了保持一致性,但我明白你的意思,会编辑谢谢。
【解决方案2】:

您可以使用列表推导,它们比 for 循环更快

a = np.array([[[ 0.01, 0.02 ]], [[ 0.03, 0.04 ]]])
print([(i[0][0], i[0][1]) for i in a])  # [(0.01, 0.02), (0.03, 0.04)]

或者:

print([tuple(l[0]) for l in a])  # [(0.01, 0.02), (0.03, 0.04)]

【讨论】:

  • 也不错! ;)
  • 较短的选择:tuple(i[0]).
  • @DirtyBit 未经他同意,您不应该更改他的解决方案,因为它没有任何问题。我的评论仅供参考。
猜你喜欢
  • 1970-01-01
  • 2015-08-07
  • 2017-10-05
  • 1970-01-01
  • 2021-09-23
  • 2015-09-16
  • 1970-01-01
  • 2018-05-03
  • 2021-06-19
相关资源
最近更新 更多