Skip to main content
 首页 » 编程设计

python之将表表示为对象

2025年05月04日18freeliver54

在 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 

我看不出有什么方法可以在没有冗余的情况下有效地存储数据。我能想到的更好的方法是使用多个字典(每行一个,每列一个),每个字典包含与字典本身关联的行或列一样多的键,加上一个包含所有关联的特殊键值(value)观。

我想类似的问题已经得到解决,这就是我问的原因。

请您参考如下方法:

作为我的其他答案的替代方案,您可以按照@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 是不可变的。如果要进行更改,请使用带有 __slots__ 的普通 class。