【问题标题】:Use value of variable rather than keyword in python numpy.savez在 python numpy.savez 中使用变量的值而不是关键字
【发布时间】:2015-11-23 18:37:37
【问题描述】:

numpy.savez

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

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']

【问题讨论】:

  • npzfile.foo.bar的实际内容从何而来?
  • 我正在从文件路径中读取一堆图像并提取描述符,理想情况下,我希望字典中的键(图像文件名)与描述符匹配。明白我的意思了吗?

标签: python arrays numpy keyword


【解决方案1】:

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

【讨论】:

  • 是的,很酷,这似乎可行,我有 C 和 C++ 知识并且知道指针,所以我想我必须传递一个指针,但不知道如何在 python 中处理它。谢谢!
猜你喜欢
  • 2021-02-28
  • 2023-01-05
  • 2015-04-07
  • 1970-01-01
  • 2021-08-02
  • 2021-10-31
  • 2019-03-12
  • 1970-01-01
  • 2013-08-04
相关资源
最近更新 更多