解决Python 使用h5py加载文件,看不到keys()的问题

python 3.x 环境下,使用h5py加载HDF5文件,查看keys,如下:

>>> import h5py
>>> f = h5py.File("a.h5",'r')
>>> f.keys()

结果看不到keys:

KeysView(<HDF5 file "a.h5" (mode r)>)

原因主要是 python2.x 和 python3.x对keys方法的返回处理不同。

官方说明如下:

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.

可见 python2 返回为list,python3 返回为view-like objects,不能直接查看。

解决方法如下:

1) 换成 python2.x 环境进行相同操作。

2) 采用如下代码:

>>> [key for key in f.keys()]

参考资料:

https://stackoverflow.com/questions/31037088/discovering-keys-using-h5py-in-python3

以上这篇解决Python 使用h5py加载文件,看不到keys()的问题就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持来客网。