gpt4 book ai didi

python-3.x - 如何初始化 Python 数据类 2D 列表?

转载 作者:行者123 更新时间:2023-12-04 01:39:19 24 4
gpt4 key购买 nike

是否可以为初始化二维数组的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_factoryfield :

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

关于python-3.x - 如何初始化 Python 数据类 2D 列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58130899/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com