park = "a park.shp"
road = "the roads.shp"
school = "a school.shp"
train = "the train"
bus = "the bus.shp"
mall = "a mall"
ferry = "the ferry"
viaduct = "a viaduct"
dataList = [park, road, school, train, bus, mall, ferry, viaduct]
print dataList
for a in dataList:
print a
#if a.endswith(".shp"):
# dataList.remove(a)
print dataList
給出了下面的輸出(所以循環工作,正確地閱讀一切):的Python(2.6.6)的endsWith()在for循環
['a park.shp', 'the roads.shp', 'a school.shp', 'the train', 'the bus.shp', 'a mall', 'the ferry', 'a viaduct']
a park.shp
the roads.shp
a school.shp
the train
the bus.shp
a mall
the ferry
a viaduct
['a park.shp', 'the roads.shp', 'a school.shp', 'the train', 'the bus.shp', 'a mall', 'the ferry', 'a viaduct']
但是當我刪除#標記運行if語句,它應該刪除以.shp結尾的字符串,字符串道路仍然在列表中?
['a park.shp', 'the roads.shp', 'a school.shp', 'the train', 'the bus.shp', 'a mall', 'the ferry', 'a viaduct']
a park.shp
a school.shp
the bus.shp
the ferry
a viaduct
['the roads.shp', 'the train', 'a mall', 'the ferry', 'a viaduct']
我注意到的其他東西,它不打印所有的字符串,當它清楚地在for循環,應該通過每個字符串?有人可以請解釋發生了什麼問題,循環保持字符串路線,但發現其他字符串以.shp結尾並正確刪除它們?
感謝, C(因爲弧10.0僅供參考,這是關於Python 2.6.6)
你不應該永遠變異的對象(如表),而你遍歷它。壞事發生。通常,在學習使用列表解析過濾之後,根本不需要使用「remove」。 – roippi
[Loop「忘記」刪除某些項目的可能的重複](http://stackoverflow.com/questions/17299581/loop-forgets-to-remove-some-items) –