在嘗試刪除未開始從列表中的特定字符串的所有文件名,我碰到下面的意外行爲:list.remove()方法不能提供預期的結果
>>> allfiles = os.listdir(mydir)
>>> allfiles
['dwcpybyext.sh', 'dwlaunch', 'libupdate.sh', 'ntpsync.sh']
>>> for f in allfiles:
... if f.startswith('n') == False:
... allfiles.remove(f)
...
>>> allfiles
['dwlaunch', 'ntpsync.sh']
這在理論上應該有每的文件名稱不是從列表中的'n'
開始的。相反,它在列表中以'd'
開頭。如果我改變循環使用if f.startswith('d') == False:
我得到['dwcpybyext.sh', 'dwlaunch', 'ntpsync.sh']
- 最後一個項目甚至不包含'd'
字符。
爲什麼我看到這種行爲?似乎不太可能是Python的list.remove()
方法中的一個錯誤 - 如果我替換del allfiles[allfiles.index(f)]
,我會得到相同的行爲,而.remove()
基本上就是這個別名。
閱讀說明在7.3節:http://docs.python.org/reference/compound_stmts.html #for – 2012-01-05 15:41:47