0
我有不知何故未能以下list.index
函數代碼段:Python列表索引怪異行爲
for line in flines:
for match in bad_data_regex.findall(line):
assert line in flines
index = flines.index(line)
flines.pop(index)
# other code that does not modify flines ....
我的代碼失敗的:
ScriptEngine.execute:Error in script Traceback (innermost last):
File "<string>", line 168, in ?
ValueError: list.index(x): x not in list
如果值確實是不該列表中,我應該在list.index
函數之前獲得AssertionError
。
我在Java版本1.6.0_18下使用Jython 2.2.1。
這怎麼可能?
編輯:
原來這是生成錯誤的代碼是不是上面我所貼。我的Jython解釋器給了我錯誤的行號,並碰巧碰到了上面的索引函數。
上面的代碼確實按照我的意圖工作,但我意識到這並不是在迭代時修改列表的最佳實踐。我會在將來儘可能避免這種情況。
感謝。事實證明,上面的代碼確實按預期工作,但我不會修改將來迭代的同一個列表。 –