[問題] list comprehension 的 scope 問題

看板Python作者 (黑駿)時間13年前 (2012/04/20 23:10), 編輯推噓0(000)
留言0則, 0人參與, 最新討論串1/1
我原本以為 [0 for i in range(5)] 這裡的 i 是區域變數 當建構出這個 list 後就會不見 但事實似乎不是如此… a = [1,1,1,1,1] for i in range(5): a[i] = [0 for i in range(3)] print i 預期結果: output: 0 1 2 3 4 a = [[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]] 實際結果: output: 2 2 2 2 2 a = [1, 1, [0, 0, 0], 1, 1] 這篇是自問自答… 剛剛自己找到答案 http://stackoverflow.com/questions/4198906/python-list-comprehension-rebind-names-even-after-scope-of-comprehension-is-thihttp://tinyurl.com/7wu5nbe 在 3 裡已經解決這個問題了~ -- 光明 的背後 是 黑暗 黑暗 的背後 還是 黑暗 由此可知 黑暗 > 光明 Q.E.D. -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 140.113.230.123
文章代碼(AID): #1FaNnNhf (Python)
文章代碼(AID): #1FaNnNhf (Python)