对于我来说,第9行似乎出了问题。在这里,我希望将TagsTable的新副本推送到字典中。我知道一旦记录了一个namedtuple字段,它就无法更改。但是,结果让我感到困惑,因为看起来值会发生变化 - 当这段代码退出mp3_tags的所有条目时[三个字典键中的任何一个] .date被设置为“1999_03_21”的最后日期
所以,有两个问题:
有没有办法将新的TagsTable推入词典?
为什么代码失败并且不允许将第二个(甚至第三个)日期写入TagsTable.date字段(因为它似乎是对同一个namedTuple的引用)?我以为你不能写第二个值?
from collections import namedtuple 2 TagsTable = namedtuple('TagsTable',['title','date','subtitle','artist','summary','length','duration','pub_date']) 3 mp3files = ['42-001.mp3','42-002.mp3','42-003.mp3'] 4 dates = ['1999_01_07', '1999_02_14', '1999_03_21'] 5 6 mp3_tags = {} 7 8 for mp3file in mp3files: 9 mp3_tags[mp3file] = TagsTable 10 11 for mp3file,date_string in zip(mp3files,dates): 12 mp3_tags[mp3file].date = date_string 13 14 for mp3file in mp3files: 15 print( mp3_tags[mp3file].date )
答案 0 :(得分:0)
看起来这是我正在寻找的修复:
from collections import namedtuple mp3files = ['42-001.mp3','42-002.mp3','42-003.mp3'] dates = ['1999_01_07', '1999_02_14', '1999_03_21'] mp3_tags = {} for mp3file in mp3files: mp3_tags[mp3file] = namedtuple('TagsTable',['title','date','subtitle','artist','summary','length','duration','pub_date']) for mp3file,date_string in zip(mp3files,dates): mp3_tags[mp3file].date = date_string for mp3file in mp3files: print( mp3_tags[mp3file].date )