如何初始化Python dataclass 二维列表?

How to initialize Python dataclass 2D list?

是否可以为 python 数据类创建一个默认初始化程序来初始化一个二维数组,即结果与

相同
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=[])

您可以使用 lambda 函数代替 default_factory 用于 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 变为:

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

另一种方法是在 初始化后(通过 __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=[])