1
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 结尾的字符串,字符串路径是否保留在列表中?

['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

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

4

2 回答 2

1

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

使用这样的列表推导:

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

然后得到:

>>> ['the train', 'a mall', 'the ferry', 'a viaduct']
于 2013-10-09T23:30:46.533 回答
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文件的列表之外没有其他目的,你可以只使用一个列表推导并跳过整个混乱。

no_shp_files = [a for a in datalist if not a.endswith('.shp')]
于 2013-10-09T23:27:51.110 回答