看板 Python 關於我們 聯絡資訊
def _product_of_two_vectors_sample_(a, b): if len(a[0]) != len(b): return None # Create the result matrix and fill it with zeros output_list=[] temp_row=len(b[0])*[0] for r in range(len(a)): -----> output_list.append(temp_row[:]) <-------------------??? for row_index in range(len(a)): for col_index in range(len(b[0])): sum=0 for k in range(len(a[0])): sum=sum+a[row_index][k]*b[k][col_index] output_list[row_index][col_index]=sum return output_list 最近在自學 這邊有個問題一直不太懂 第8行的附加裡面的temp_row[:]和 output_list.append(temp_row) 之間有什麼不同 因為我自己會打temp_row 但是跑出來的結果是錯的 -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 140.113.63.51 ※ 文章網址: https://www.ptt.cc/bbs/Python/M.1459048662.A.3E6.html
LiloHuang: temp_row[:] 會做出一份拷貝,反之則是參照原先的list 03/27 11:25
LiloHuang: >>> foo = [1,2,3] 03/27 11:26
LiloHuang: >>> id(foo) 03/27 11:26
LiloHuang: 33920784 03/27 11:26
LiloHuang: >>> bar = foo 03/27 11:26
LiloHuang: >>> id(bar) 03/27 11:26
LiloHuang: 33920784 03/27 11:26
LiloHuang: >>> bar = foo[:] 03/27 11:26
LiloHuang: >>> id(bar) 03/27 11:26
LiloHuang: 33919424 03/27 11:27
LiloHuang: 留意到了 object id 改變了嗎 :P 03/27 11:29
ghostreporty: 這有點像Java new的概念 03/27 12:50
paulyanzi: 原來有 id 這個東西,id 這功能平常有什麼機會使用到嗎 03/27 13:58
LiloHuang: 當需要識別物件或者除錯時,就是使用 id(obj) 的場合 03/27 15:01
LiloHuang: 而 CPython 剛好使用物件的記憶體位址來當作 id 03/27 15:02
LiloHuang: 延伸閱讀官方文件 https://goo.gl/g3mzEZ 03/27 15:02
DearYoyoDon: 大概懂了!! 感謝~ >////< 03/28 01:32
ENEP: 推 原來[:]會作copy 那dict有類似的作法嗎 03/28 01:54
uranusjr: dict 直接呼叫 .copy() 即可 03/28 02:08