我创建了一个嵌套的namedtuples(练习我的不可变函数编程技巧)的数据结构,但我努力寻找一种简单的方法来替换嵌套namedtuples中的值。Python:简单的方法来替换嵌套的namedtuple属性?
比方说,我有一个数据结构是这样的:
from collections import namedtuple
Root = namedtuple("Root", "inventory history")
Inventory = namedtuple("Inventory", "item1 item2")
Item = namedtuple("Item", "name num")
Event = namedtuple("Event", "action item num")
r = Root(
inventory=Inventory(
item1=Item(name="item1", num=1),
item2=Item(name="item2", num=2)
),
history=(
Event(action="buy", item="item1", num=1),
Event(action="buy", item="item2", num=2)
)
)
# Updating nested namedtuples is very clunky
num_bought = 4
r_prime = r._replace(
history = r.history + (Event(action="buy", item="item2", num=num_bought),),
inventory = r.inventory._replace(
item2 = r.inventory.item2._replace(
num = r.inventory.item2.num + num_bought
)
)
)
# Contrast with the ease of using a version of this based on mutable classes:
r.history += Event(action="buy", item="item2", num=num_bought),
r.inventory.item2.num += num_bought
正如你所看到的,更改值在库存中的项目是一个相当痛苦,幸亏)被迫单独所有更新的值嵌套在下面,b)无法访问像+=
这样的运算符。
如果我更新的库存中的物品是动态的,这要归功于getattr
随处可见。
有没有更简单的方法来处理这个问题?
为什么不使用字典或类? – jonrsharpe
'nametuple's只是不适合你的正确数据容器。 – roippi
@jonrsharpe我试图在这个项目上练习我的函数式编程技巧,而不可变的数据结构是函数式编程的核心组件。除此之外,如果可能的话,我希望从不变数据结构中清楚价值更新的来源,从而帮助减少错误计数。 – spiffytech