Python(2.6.6)for循环中的endswith()

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

谢谢, 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/

相关文章:

python - 在单元测试中使用 pyodbc

python - 从 python 编辑 .RAR 文件注释

python - 如何从 Odoo 10 中的自定义模块修改 noupdate ="1"XML 记录?

python - 为什么 deepcopy 不创建对 lambda 函数的新引用?

arrays - Kernighan 和 Ritchie 的主题 1.6

python - 连接两个列表的笛卡尔积的字符串(最好没有 for 循环)

json - python json中的ordered_dict

python - 输入数组相等时索引矩阵元素

python - 在 Python 中执行多个列表理解的最有效方法

javascript - 使用数组和映射创建 x 对象