我正在解析来自我运行的各种测试的多个数据文件,并且我想将每个测试的值分组在属于集合的变量中。例如,一对集合是:
type_GA_RX1 = collections.namedtuple('type_GA_RX1',
['GA_RX1',
'GA_RX1logmag',
'GA_RX1mag',
'GA_RX1ph'])
type_GA_RX2 = collections.namedtuple('type_GA_RX2',
['GA_RX2',
'GA_RX2logmag',
'GA_RX2mag',
'GA_RX2ph'])
当我遍历这些文件时,我想做这样的事情:
keys=dataGA.keys() # dictionary of parsed file data
for key in keys:
if len(dataGA[key]) >0:
GA_RX1logmag = np.array(dataGA[key].RX1_log_mag)
GA_RX1mag = 10**(GA_RX1logmag/20)
GA_RX1 = np.array(dataGA[key].RX1_real +1j*dataGA[key].RX1_imag)
GA_RX1ph = np.array(dataGA[key].RX1_phase)
,然后赋值给集合类型:
type_GA_RX1[key].GA_RX1logmag = GA_RX1logmag
type_GA_RX1[key].GA_RX1mag = GA_RX1mag
type_GA_RX1[key].GA_RX1 = GA_RX1
type_GA_RX1[key].GA_RX1ph = GA_RX1ph
然而,我不能索引到一个'type'对象;我得到这个错误:
type_GA_RX1[key].GA_RX1logmag= GA_RX1logmag
TypeError: 'type' object is not subscriptable
我该怎么做?或者,这不是我想做的吗?如何创建集合数组?
为了清晰起见,dataGA
看起来像这样(节选):
{0: RX1_real RX1_imag RX2_real ... distance RX2_log_mag RX1_log_mag
61 -0.019780 -0.005127 0.010010 ... 1.0 -38.426806 -33.793076
62 -0.018310 -0.010740 0.007812 ... 4.0 -38.190809 -33.462052
63 -0.016600 -0.012450 0.006348 ... 8.0 -38.523323 -33.659638
64 -0.020510 -0.005127 0.010010 ... 18.0 -38.426806 -33.497447
65 -0.015140 -0.013670 0.005127 ... 25.0 -38.488333 -33.808143
.. ... ... ... ... ... ... ...
477 -0.006104 -0.018310 -0.009521 ... 9795.0 -37.416049 -34.288563
478 -0.008545 0.017820 0.013180 ... 9799.0 -37.482664 -34.083018
479 0.000000 0.019290 0.010990 ... 9802.0 -37.584010 -34.293355
495 0.018800 0.004395 -0.005127 ... 9803.0 -36.574736 -34.285753
480 -0.008301 -0.017330 -0.007324 ... 9804.0 -37.062341 -34.326965
[401 rows x 9 columns],
1: RX1_real RX1_imag RX2_real ... distance RX2_log_mag RX1_log_mag
61 -0.019780 -0.005127 0.010010 ... 1.0 -38.426806 -33.793076
62 -0.018310 -0.010740 0.007812 ... 4.0 -38.190809 -33.462052
63 -0.016600 -0.012450 0.006348 ... 8.0 -38.523323 -33.659638
type_GA_RX1[key].GA_RX1logmag = GA_RX1logmag type_GA_RX1[key].GA_RX1mag = GA_RX1mag type_GA_RX1[key].GA_RX1 = GA_RX1 type_GA_RX1[key].GA_RX1ph = GA_RX1ph
这里有两三个问题:
- 您从未创建
type_GA_RX1
的实例 - 如果你创建了一个,namedtuple实例是不可变的,所以你不能在创建它们之后分配属性。你需要将值直接传递给初始化器。
- 您似乎试图使用
type_GA_RX1[key]
,如果type_GA_RX1
是一个字典,但您没有在任何地方创建字典。 - 我也怀疑你实际上并不想把整个数组的值放在一个
type_GA_RX1
实例中,而只是一个值。
我想你的意思是:
GA_RX1_instances = {}
for key, data in dataGA.items():
if len(data) > 0:
logmag = data.RX1_log_mag
GA_RX1_instances[key] = type_GA_RX1(
GA_RX1logmag = logmag
GA_RX1mag = 10**(logmag/20)
GA_RX1 = data.RX1_real + 1j*data.RX1_imag
GA_RX1ph = data.RX1_phase
)
其中GA_RX1logmag = ...
等不是局部变量,而是关键字参数。