在 python3 中使用 h5py 发现密钥

2023-12-23

In python2.7,我可以分析一个hdf5文件密钥使用

$ python
>>> import h5py
>>> f = h5py.File('example.h5', 'r')
>>> f.keys()
[u'some_key']

然而,在python3.4,我得到了不同的东西:

$ python3 -q
>>> import h5py
>>> f = h5py.File('example.h5', 'r')
>>> f.keys()
KeysViewWithLock(<HDF5 file "example.h5" (mode r)>)

What is KeysViewWithLock,以及如何在 Python3 中检查我的 HDF5 密钥?


来自 h5py 的网站(http://docs.h5py.org/en/latest/high/group.html#dict-interface-and-links http://docs.h5py.org/en/latest/high/group.html#dict-interface-and-links):

当使用 Python 3 中的 h5py 时,keys()、values() 和 items() 方法将返回类似视图的对象而不是列表。这些物体 支持集装箱船测试和迭代,但不能像 列表。

这解释了为什么我们无法查看它们。最简单的答案是将它们转换为列表:

>>> list(for.keys())

不幸的是,我在 iPython 中运行,它使用命令“l”。这意味着该方法行不通。

为了实际查看它们,我们需要利用集装箱船测试和迭代。集装箱船测试意味着我们必须已经知道密钥,所以就这样了。幸运的是,使用迭代很简单:

>>> [key for key in f.keys()]
['mins', 'rects_x', 'rects_y']

我创建了一个简单的函数来自动执行此操作:

def keys(f):
    return [key for key in f.keys()]

然后你得到:

>>> keys(f)
['mins', 'rects_x', 'rects_y']
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在 python3 中使用 h5py 发现密钥 的相关文章

随机推荐