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 结尾的其他字符串并正确删除了它们?
谢谢, C
(仅供引用,这是在 Python 2.6.6 上,因为 Arc 10.0)
最佳答案
您正在改变列表并导致索引跳过。
使用这样的列表理解:
[d for d in dataList if not d.endswith('.shp')]
然后得到:
>>> ['the train', 'a mall', 'the ferry', 'a viaduct']
关于Python(2.6.6)for循环中的endswith(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19284502/