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

标签 python arrays database numpy dictionary

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

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 包实现这种数据结构?

最佳答案

我自己做的。它的名字叫鸭子。它目前位于 Artemis 的主分支中。下面是一些演示其用法的代码:

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

关于用于树结构的类似 Python numpy 的接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47012227/

相关文章:

python - 在 Python 中使用命名空间从 XML 节点检索属性

python - matplotlib:在 3d 极坐标图中填充线下

javascript - 使用 Javascript 中的值从多维数组中删除元素

database - 用于移动设备的 Flex - 使用数据库

python - 如何在 Python 中发送和接收 HTTP POST 请求

php - 从数组输入数据时如何防止mysql中的重复输入?

c - 如何使用指针仅指向数组的一半

Mysql查询从2个表中获取数据

sql - 如何在通用模式上对数据变量方差进行建模? SQL

python - 在 python 中创建独立于平台的 GUI 可执行文件