[問題] list comprehension 的 scope 問題
我原本以為 [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-thi
縮 http://tinyurl.com/7wu5nbe
在 3 裡已經解決這個問題了~
--
光明 的背後 是 黑暗
黑暗 的背後 還是 黑暗
由此可知 黑暗 > 光明 Q.E.D.
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 140.113.230.123
Python 近期熱門文章
PTT數位生活區 即時熱門文章