如何初始化Python数据类2D列表?

时间:2019-09-27 08:42:39

标签: python-3.x python-3.7 python-dataclasses

可以为Python数据类创建默认的初始化程序,以初始化2D数组,即与

相同
from dataclasses import dataclass, field
from typing import List
MAX = 5
@dataclass
class AlgoData:
    list2D: List[List[int]]  # = ???
    list1D: List[int] = field(default_factory=list)

b = [[] for m in range(MAX)]
a = AlgoData(b)

,但没有b参数。结果:

AlgoData(list2D=[[], [], [], [], []], list1D=[])

2 个答案:

答案 0 :(得分:3)

您可以使用lambda函数代替default_factory的{​​{1}}:

field

from dataclasses import dataclass, field from typing import List MAX = 5 @dataclass class AlgoData: list2D: List[List[int]] = field(default_factory=lambda: [[] for m in range(MAX)]) list1D: List[int] = field(default_factory=list) a = AlgoData() 变为:

a

答案 1 :(得分:0)

另一种选择是在初始化后(通过__post_init__)分配属性

给出

from typing import List

from dataclasses import dataclass, field


MAX = 5

代码

@dataclass
class AlgoData:
    """Algorithm data."""
    list1D: List[int] = None
    list2D: List[List[int]] = field(default_factory=list)

    def __post_init__(self):

        self.list2D = [[] for _ in range(MAX)]

演示

a = AlgoData()
a
# AlgoData(list2D=[[], [], [], [], []], list1D=[])