2017-10-30 16 views
1

私はしばしば、dictと配列の間の何かである柔軟なデータ構造を必要としています。次の例が説明されることを願っています:木構造のためのPythonのnumpyのようなインタフェース

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パッケージはありますか?

+0

このヘルプはない:ここでは、その使用を実証するいくつかのコードですhttps://stackoverflow.com/questions/2358045/how-can-i-implement-a-tree-in-python-are-there-any -built-in-data-structures-in – doctorlove

答えて

0

ありがとうございましたStackOverflow!だから私はそれを自分で作った。それはダックと呼ばれています。現在、マスターブランチ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 
関連する問題