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

Ale*_*lex 9 python numpy

这是我拥有的 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)
Run Code Online (Sandbox Code Playgroud)

我发现了一个类似的问题,但没有元组,所以建议的ravel().tolist()方法在这里对我不起作用。

meo*_*dog 13

# 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))))
...
Run Code Online (Sandbox Code Playgroud)

  • 你有什么理由把“2L”放在那里?在 Python 3 中,所有整数都是长整数,因此我建议删除那些 `L`,以免新 Python 程序员认为这是“好的风格”甚至是“必需的”。 (3认同)