亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

關于python 的shelve模塊,求大俠

關于python 的shelve模塊,求大俠

拉風的咖菲貓 2018-07-18 15:04:08
#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


查看完整回答
反對 回復 2018-07-18
?
瀟瀟雨雨

TA貢獻1833條經驗 獲得超4個贊

>>> import shelve 
>>> help(shelve)

查看完整回答
反對 回復 2018-07-18
  • 2 回答
  • 0 關注
  • 459 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號