Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/330.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
用于树结构的类似Python numpy的接口_Python_Arrays_Database_Numpy_Dictionary - Fatal编程技术网

用于树结构的类似Python numpy的接口

用于树结构的类似Python numpy的接口,python,arrays,database,numpy,dictionary,Python,Arrays,Database,Numpy,Dictionary,我发现自己经常需要一个灵活的数据结构,它介于dict和数组之间。我希望下面的例子能够说明: 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['

我发现自己经常需要一个灵活的数据结构,它介于dict和数组之间。我希望下面的例子能够说明:

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包?

我自己做的。它叫鸭子。它目前居住在美国的主支部。下面是一些演示其用法的代码:

from artemis.general.duck import Duck
import numpy as np
import pytest

# Demo 1: Dynamic assignment
a = Duck()
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 list(a['b', 1, :]) == [6, 7]
assert a['b', :, 'subfield1'] == [4, 6]
assert a['a', 'aa2'] == 2
assert np.array_equal(a['b'].to_array(), [[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']

# Demo 2: Sequential and Sliced Assignment
# Here we show another way to create the same structure as above
# 1) You can assign to a slice
# 2) You can use the "next" builtin like an index to append to the structure.
b = Duck()
b['a', :] = {'aa1': 1, 'aa2': 2}  # Note: when assigning with dict, keys are sorted before insertion (OrderedDict order is kept though).
b['b', next, :] = {'subfield1': 4, 'subfield2': 5}
b['b', next, :] = {'subfield1': 6, 'subfield2': 7}
assert b==a
这是否有助于: