Skip to main content
 首页 » 编程设计

Python如何编辑存储在列表中的namedtuple中的数据

2025年05月04日17tintown

import struct 
from collections import namedtuple 
 
StructPageNum = namedtuple('FDResult', ['DeviceID', 'PageNum','PicSize','PicData']) 
PageNumList = [] 
 
Node = StructPageNum(DeviceID='NR09', PageNum=[],PicSize=100,PicData='') 
PageNumList.append(Node) 
 
PageNumList[0].PicData = 'hello' //how to do at here? 

问题

如何修改PicData的值?

请您参考如下方法:

在我看来你可以使用 _replace一个 namedtuple 的方法可以很容易地做到这一点:

PageNumList[0] = PageNumList[0]._replace(PicData='hello') 

这会在您的 PageNumList 中放置一个新的 namedtuple,除了我们更改了 PicData“属性外,它看起来很像旧的 namedtuple ”。您不能编辑已有的命名元组,因为 namedtuple 是不可变的(就像它们未命名的对应物:元组)