在 python3 中使用 h5py 发现密钥

Discovering keys using h5py in python3

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)>)

什么是 KeysViewWithLock,我如何检查 Python3 中的 HDF5 密钥?

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

When using h5py from Python 3, the keys(), values() and items() methods will return view-like objects instead of lists. These objects support containership testing and iteration, but can’t be sliced like lists.

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

>>> list(for.keys())

不幸的是,我运行东西在iPython,它使用命令'l'。这意味着这种方法行不通。

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

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