python - 类型错误 : 'KeysView' object does not support indexing

标签 python python-3.x python-2.7 key h5py

我在尝试直接在 python 中分析来自 HDF5 文件的数据时遇到此错误。这段代码在我的 linux 机器上运行良好,但我在 Spyder3 的 mac 上尝试编译相同的脚本时遇到此错误。我尝试使用我的 mac 的原因是因为我不确定如何在 linux 终端上编写和运行脚本。

def dataProcessing(datafile):
import h5py
import numpy as np
import matplotlib.pyplot as plt
import pylab

f = h5py.File(datafile, 'r')
#print(f)
#print("Keys: %s" % f.keys())
groupKeyVal = f.keys()[4]
rawData = list(f[groupKeyVal])

rawDataMat = np.matrix(rawData)

for i in range(0,len(rawDataMat[:,0])):
    fig = rawDataMat[i,:]
    wav = np.squeeze(np.asarray(fig))
    plt.plot(wav)
    plt.show()

最佳答案

在 Python3 中,字典 keys 返回一个“view”,而不是一个可索引的列表。

In [80]: d={'a':1, 'b':2}
In [81]: d.keys()
Out[81]: dict_keys(['a', 'b'])
In [82]: d.keys()[0]
....
TypeError: 'dict_keys' object does not support indexing

类似地,对于来自 h5 组的键的字典

In [86]: f = h5py.File('data.h5')
In [87]: f.keys()
Out[87]: KeysView(<HDF5 file "data.h5" (mode r+)>)
In [88]: f.keys()[0]
....
TypeError: 'KeysView' object does not support indexing
In [89]: list(f.keys())
Out[89]: ['dset', 'dset1', 'vset']
In [90]: list(f.keys())[1]
Out[90]: 'dset1'

添加 list 有点麻烦,但它可以使键的迭代更高效。

In [92]: for k in f.keys():print(f[k])
<HDF5 dataset "dset": shape (3, 5), type "<f8">
<HDF5 dataset "dset1": shape (2, 3, 10), type "<f8">
<HDF5 dataset "vset": shape (100,), type "|O">

关于python - 类型错误 : 'KeysView' object does not support indexing,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45426579/

相关文章:

python - 在 Python 中获取 DictReader 标题的特殊情况

python - 从多个 DIV 选择要打印的 URL

Python - 遍历多维字典

python - 使用python替换文件中的功能 block

python - 将excel中的数据粘贴到网站,点击 "track"

python - 在 Python 3.5 中,如何将函数指定为类型提示?

python-2.7 - 使用 Python 循环 csv 文件的指定行

python - .py 文件中的 Visual Studio Code SQL 语法突出显示

python - 在 python 数据框中发送 token 后,Word_tokenize 不起作用

python - Flask 应用程序的内存存储