【发布时间】:2017-10-30 09:50:07
【问题描述】:
我发现自己经常需要一种介于字典和数组之间的灵活数据结构。我希望下面的例子能说明:
a = ArrayStruct()
a['a', 'aa1'] = 1
a['a', 'aa2'] = 2
a['b', 0, 'subfield1'] = 4
a['b', 0, 'subfield2'] = 5
a['b', 1, 'subfield1'] = 6
a['b', 1, 'subfield2'] = 7
assert a['a', 'aa2'] == 2
assert all(a['b', 1, :] == [6, 7])
assert all(a['b', :, 'subfield1'] == [4, 6])
assert all(a['b', :, :] == [[4, 5], [6, 7]])
with pytest.raises(KeyError): # This should raise an error because key 'a' does not have subkeys 1, 'subfield1'
x = a[:, 1, 'subfield1']
在我去(重新)发明轮子之前。是否有实现这种数据结构的现有 Python 包?
【问题讨论】:
标签: python arrays database numpy dictionary