看板 Python 關於我們 聯絡資訊
※ 引述《jimmylin212 (JimmyG)》之銘言: : 想請一個程式片段的錯誤 : list = [ [1,a],[1,b],[2,c],[2,d],[3,e],[4,f],[5,g] ] : for i in range(0, len(list)): : if list[i][0] == 1: : list.pop(i) : 當我執行這段程式的時候最後結束都會 index out of range : 最後大概會有一兩個長度的誤差,就是會讀到空的地方 : 想請問會出現這種問題是為什麼呢? : 另外要怎麼解決呢? 首先range(0,len(list)) 得到i的範圍是0~6 從loop分析, 一開始i=0, 所以list.pop(0)是刪掉[1, 'a'] 所以list變成[[1, 'b'], [2, 'c'], [2, 'd'], [3, 'e'], [4, 'f'], [5, 'g']] 然後你的i的範圍剩下1~6, list根本就沒有list[6]了 所以才會出現list index out of range的錯誤 -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 123.193.77.93
jimmylin212:噢 i 一開始就定義好了,之後不會跟著 list 變換嗎? 11/22 19:28
cibs:i又不是依存在list上面 11/23 01:41
suzuke:樓上的意思是? 11/23 10:36
apua:i是依存在range(len(L)),而不是依存L 11/24 00:12