将表表示为对象

时间:2013-04-25 10:21:52

标签: python python-3.x

是否有一种标准方法来表示包含Python中某些关系数据的表?我的意思是,像这样:

      Singular   Plural
1st.  I make     we make
2nd.  you make   you make
3d.   he makes   they make

我希望按行和按列访问数据,如下所示:

1st. Singular -> I make
1st.          -> I make, we make
Plural 3d.    -> they make
Plural        -> we make, you make, they make

我没有任何方法可以有效地存储数据,没有冗余。我能想到的更好的是使用多个字典(每行一个,每列一个),每个字典包含与字典本身相关的行或列一样多的键,加上一个包含所有关联的特殊键值。

我想这样的事情已经解决了,这就是我问的原因。

2 个答案:

答案 0 :(得分:4)

作为我的其他答案的替代方案,您可以按照@jamylak的建议使用namedtuple

from collections import namedtuple

class Verb(namedtuple("_Verb",  # arbitrary class name/tag
                      ["singular1", "singular2", "singular3",
                       "plural1", "plural2", "plural3"])):
    @property
    def singular(self):
        return (self.singular1, self.singular2, self.singular3)

    # similarly for plural

    @property
    def first_person(self):
        return (self.singular1, self.plural1)

    # similarly for 2nd and 3rd person

现在“make”可以表示为

Verb("make", "make", "makes", "make", "make", "make")

同样,这可以通过利用英语结合的简单性来优化。

此解决方案的缺点是它不允许更改表中的单个字段,因为namedtuple是不可变的。如果您想进行更改,请使用普通的class __slots__

答案 1 :(得分:2)

您可以通过将每个动词表示为扁平元组来消除冗余:

("make", "make", "makes", "make", "make", "make")

然后为索引创建dict映射键:

ind_from_key = {'1st': (0, 3),
                ...,
                'singular': (0, 1, 2),
                ...,
                '1st singular': (0,)}

当然,查找会变得更复杂,因为您必须进行间接查找:

def conjugation(verb, conj):
    indices = ind_from_key[conj]
    return [CONJUGATION[verb][i] for i in indices]

请注意,英语动词的结合非常简单,可以进一步优化;复数形式在语法人群中总是相同的。

至于原始问题:不,没有单一的标准方法来表示Python中的关系数据。如果你的关系变得比口头变形更复杂,而且你有很多数据,那么你可能想要查看SQLite或其他数据库解决方案,或许与SQLAlchemy一起使用。