TypeError:“KeyView”对象不支持索引

2024-10-03 23:28:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我在试图直接用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()

Tags: import脚本linuxmacas错误npplt
1条回答
网友
1楼 · 发布于 2024-10-03 23:28:12

在Python3中,dictionarykeys返回一个“视图”,而不是一个可索引列表

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

相关问题 更多 >