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

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

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

x_name = 'foo'
y_name = 'bar'

np.savez(outfile, x_name=x, y_name=y)

然后

npzfile.files
['foo', 'bar']

最佳答案

您可以创建一个字典,然后使用 ** 将其内容以关键字参数的形式传递给 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']

关于python - 在 python numpy.savez 中使用变量值而不是关键字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33878179/

相关文章:

用于小数字的 Python numpy linspace

python - 给定biopython的GenBank登录码如何获取学名?

python - 从字典中分配和调用内置函数 (Python)

php - 合并 Mysql 列输出作为 php 中的逗号分隔

python - 从一组 x、y 坐标计算表面的质心

Python Pandas 时间戳减法与 Numpy

python - 在pyspark中加载大于内存的hdf5文件

python - 使用 cython 加速 itertools 组合

java.lang.ArrayIndexOutOfBoundsException : 0 In the most simple program

从 stdin 计算简单赋值运算符 "="