for循环中的Python(2.6.6)endswith()
给出以下输出(以便循环正常工作并正确读取所有内容): 但是当我删除#标记以运行if语句时,如果它应该删除以.shp结尾的字符串,那么stringroad仍然在列表中for循环中的Python(2.6.6)endswith(),python,for-loop,python-2.6,ends-with,Python,For Loop,Python 2.6,Ends With,给出以下输出(以便循环正常工作并正确读取所有内容): 但是当我删除#标记以运行if语句时,如果它应该删除以.shp结尾的字符串,那么stringroad仍然在列表中 ['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
['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']
我还注意到,当它在一个for循环中时,它不会打印所有的字符串,而这个for循环应该遍历每个字符串?有人能解释一下哪里出了问题,循环保留了字符串road,但找到了以.shp结尾的其他字符串并正确删除了它们吗
谢谢,
C
(仅供参考,这是在Python2.6.6上,因为ARC10.0)从您迭代的同一列表中删除项目几乎总是会导致问题。复制一份原始列表,并迭代该列表;这样你就不会漏掉任何东西
['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']
当然,如果这个循环除了创建一个没有.shp
文件的列表之外没有其他用途,那么您可以只使用一个,跳过整个混乱
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
从正在迭代的同一列表中删除项目几乎总是会导致问题。复制一份原始列表,并迭代该列表;这样你就不会漏掉任何东西
['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']
当然,如果这个循环除了创建一个没有.shp
文件的列表之外没有其他用途,那么您可以只使用一个,跳过整个混乱
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
您正在改变列表并导致索引跳过 使用如下列表:
no_shp_files = [a for a in datalist if not a.endswith('.shp')]
然后得到:
[d for d in dataList if not d.endswith('.shp')]
您正在改变列表并导致索引跳过 使用如下列表:
no_shp_files = [a for a in datalist if not a.endswith('.shp')]
然后得到:
[d for d in dataList if not d.endswith('.shp')]
在迭代对象(如列表)时,不应对其进行变异。坏事发生了。通常,在您学会使用列表理解进行过滤后,您根本不需要使用
remove
。在迭代对象(如列表)时,您可能的重复对象不应发生变化。坏事发生了。一般来说,在您学会使用列表理解进行过滤后,您根本不需要使用删除
。这三个答案可能都是重复的,两个使用列表理解,一个简单地创建一个新列表。两种方法都试过了,效果很好,干杯!感谢所有三个答案,两个使用列表理解,一个简单地创建一个新列表。两种方法都试过了,效果很好,干杯!感谢所有三个答案,两个使用列表理解,一个简单地创建一个新列表。两种方法都试过了,效果很好,干杯!感谢所有三个答案,两个使用列表理解,一个简单地创建一个新列表。两种方法都试过了,效果很好,干杯!