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

标签 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)

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

最佳答案

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

关于python - 如何有效地将 numpy ndarray 转换为元组列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55336870/

相关文章:

python - 无论使用 Numpy 的元素顺序如何,如何在不同数组中找到相同的行?

python - Numpy 排列但步长加倍

arrays - Numpy 迭代和追加

python - Django 单元测试随机失败

python - 向按年线分组的时间序列添加标签 - Matplotlib、Python

python - Numbapro : No speed-up for Matrix Multiplication

python - Numpy 点积结果为 `IndexError: only integers, slices...`

python - 如何使用 univ_pos 参数实现 spacy lemmatizer

python - 在Python中将音频输出从一个函数重定向到另一个函数

python - 处理消歧错误?