如何高效地将numpy的ndarray转换为元组列表?

15

你为什么要使用列表? - DirtyBit
PS. 你不能将两个元素添加到一个列表中。 - DirtyBit
@DirtyBit 对不起,刚刚编辑了问题。 - Alex
2个回答

18
# 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))))
...

3
你为什么要加上 2L 这个后缀?在 Python 3 中,所有的整数都是长整型,因此我建议删除那些 L,以免让新手 Python 程序员误认为这是“良好的风格”或者“必需的”。 - NOhs
@NOhs 我这么做是为了保持一致性,但我理解你的意思,会进行编辑,谢谢。 - meowgoesthedog

3
您可以使用列表推导式,它们比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)]

也不错!;) - DirtyBit
2
更短的替代方案:tuple(i[0]) - meowgoesthedog
2
@DirtyBit,你不应该在未经他同意的情况下修改他的解决方案,因为它本身没有任何问题。我的评论只是为了以后参考。 - meowgoesthedog

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接