#source1 #from <python基础教程> import shelve s = shelve.open('temp.dat') s['x'] = ['a', 'b', 'c'] s['x'].append('d') print s['x'] -------------------------- >>>['a', 'b', 'c'] 书上的解释:1.列表['a', 'b', 'c']存储在x下; 2.获得存储的表示, 并且根据它创建新的列表,而'd'加到这个副本.修改的版本还没有被保存! 3.最终,再次获得原始版本----没有'd' 第2条没想明白,为什么会创建新的列表.(source3中为什么没创建,或者说为什么与source3的结果不一样.) ======================== #source2 import shelves = shelve.open('temp.dat')s['x'] = ['a', 'b', 'c'] s. close() s = shelve.open('temp.dat') s['x'].append('d')print s['x'] -------------------------- >>>['a', 'b', 'c'] 这条是看到别的大神有说是因为s['x'] = ['a', 'b', 'c']这条执行完后没有写回, s. close()是确保其结果写回.那s['x'].append('d')结果为什么还是和source1一样. ======================= #source3 s = {} s['x'] = ['a', 'b', 'c'] s['x'].append('d') print s['x'] ------------------------- >>>['a', 'b', 'c', 'd']
2 回答
牧羊人nacy
TA贡献1862条经验 获得超7个赞
文档:
Normally, d[key] returns a COPY of the entry. This needs care when
mutable entries are mutated: for example, if d[key] is a list,
d[key].append(anitem)
does NOT modify the entry d[key] itself, as stored in the persistent
mapping -- it only modifies the copy, which is then immediately
discarded, so that the append has NO effect whatsoever. To append an
item to d[key] in a way that will affect the persistent mapping, use:
data = d[key]
data.append(anitem)
d[key] = data
- 2 回答
- 0 关注
- 425 浏览
添加回答
举报
0/150
提交
取消