打印 numpy 数组以进行复制和粘贴

Nic*_*mer 6 python numpy

有时,我想要print一个 numpy 数组,只是将其从命令行复制到其他地方。标准__repr__很接近,但缺少逗号:

import numpy as np

a = np.random.rand(5, 2)
print(a)
Run Code Online (Sandbox Code Playgroud)
[[0.66585668 0.5793219 ]
 [0.28048686 0.11019737]
 [0.41359919 0.69354774]
 [0.02062253 0.85507001]
 [0.05443759 0.51366551]]
Run Code Online (Sandbox Code Playgroud)

有什么提示吗?

小智 1

假设您想要的输出如下:

[
    [0.5838947919313026, 0.05795999970550392],
    [0.9737053546477267, 0.7160755144818707],
    [0.17361370495727824, 0.09849691691484186], 
    [0.863423476768234, 0.7065666761268419],
    [0.18712559034118503, 0.21525050659592326]
]
Run Code Online (Sandbox Code Playgroud)

您可以使用列表理解和list构造函数来执行此操作:

import numpy as np
a = np.random.rand(5, 2)
print([list(i) for i in a])
Run Code Online (Sandbox Code Playgroud)