KZi*_*vas 3 python python-dataclasses
我有以下类型的对象列表:
@dataclass
class Feature:
name: str
active: bool
Run Code Online (Sandbox Code Playgroud)
我的清单是:
features = [Feature("name1",False), Feature("name2",False), Feature("name3",True)]
Run Code Online (Sandbox Code Playgroud)
我想取回包含所有功能的列表,但将其active属性切换为True. 我尝试map()这样使用:
active_features=list(map(lambda f: f.active=True,features))
Run Code Online (Sandbox Code Playgroud)
但这给了我一个错误expected parameter。如何才能实现这一目标?
请注意 ,我认为这是从示例中得出的,但我想我应该澄清一下。我想用一些简短的内联方法来做到这一点,而不需要按照一些答案的建议定义一个新的单独函数,但也许不能像这样完成?
您可以调用数据类replace,它将创建具有更改后的属性的副本:
from dataclasses import dataclass, replace
@dataclass
class Feature:
name: str
active: bool
features = [Feature("used-to-be", False), Feature("maybe", False)]
active_features = [replace(x, active=True) for x in features]
print(active_features) # should be active
print(features) # should be intact
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
696 次 |
| 最近记录: |