Python(2.6.6)endwith()in for循环

时间:2013-10-09 23:23:23

标签: python for-loop python-2.6 ends-with

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

给出以下输出(因此循环正在工作并正确读取所有内容):

['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结尾的字符串,字符串road仍在列表中?

['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结尾的其他字符串并正确删除它们?

谢谢, ç

(仅供参考,这是在Python 2.6.6上,因为Arc 10.0)

2 个答案:

答案 0 :(得分:0)

从您正在迭代的同一列表中删除项目几乎总会导致问题。制作原始列表的副本并对其进行迭代;这样你就不会跳过任何东西。

for a in dataList[:]: # Iterate over a copy of the list
    print a
    if a.endswith(".shp"):
        dataList.remove(a) # Remove items from the original, not the copy

当然,如果此循环除了创建没有.shp文件的列表之外没有任何其他目的,您可以使用一个list comprehension并跳过整个混乱。

no_shp_files = [a for a in datalist if not a.endswith('.shp')]

答案 1 :(得分:0)

您正在改变列表并导致索引跳过。

使用这样的列表理解:

[d for d in dataList if not d.endswith('.shp')]

然后得到:

>>> ['the train', 'a mall', 'the ferry', 'a viaduct']