在python numpy.savez中使用变量的值而不是关键字

use*_*241 1 python arrays numpy keyword

numpy.savez

在最后一个示例中,将 savez 与 **kwds 一起使用,数组与关键字名称一起保存。

outfile = TemporaryFile()
np.savez(outfile, x=x, y=y)
outfile.seek(0)
npzfile = np.load(outfile)
npzfile.files
['y', 'x']
npzfile['x']
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
Run Code Online (Sandbox Code Playgroud)

我将如何使用变量的实际值,例如:

x_name = 'foo'
y_name = 'bar'

np.savez(outfile, x_name=x, y_name=y)
Run Code Online (Sandbox Code Playgroud)

然后

npzfile.files
['foo', 'bar']
Run Code Online (Sandbox Code Playgroud)

DSM*_*DSM 5

您可以制作一个字典,然后使用**它以关键字参数的形式将其内容传递给np.savez. 例如:

>>> x = np.arange(10)
>>> y = np.sin(x)
>>> x_name = 'foo'
>>> y_name = 'bar'
>>> outfile = TemporaryFile()
>>> np.savez(outfile, **{x_name: x, y_name: y})
>>> outfile.seek(0)
>>> npzfile = np.load(outfile)
>>> npzfile.files
['foo', 'bar']
Run Code Online (Sandbox Code Playgroud)