【发布时间】:2017-06-12 05:50:10
【问题描述】:
我想运行一个 for 循环来检查字符串中的每个字母,如果 wanted 列表包含该字母,那么我希望该字母保留,如果 wanted 不包含该字母,那么我想删除它。
phrase = "Don't panic"
pList = list(phrase)
print(pList)
wanted = ["o","n","t","a","p"]
for anything in pList:
print("Now checking", anything)
if anything not in wanted:
print("Removed",anything)
pList.remove(anything)
elif anything in wanted:
print("Didn't remove", anything)
print(pList)
以下代码返回此输出-
['D', 'o', 'n', "'", 't', ' ', 'p', 'a', 'n', 'i', 'c']
Now checking D
Removed D
Now checking n
Didn't remove n
Now checking '
Removed '
Now checking
Removed
Now checking a
Didn't remove a
Now checking n
Didn't remove n
Now checking i
Removed i
['o', 'n', 't', 'p', 'a', 'n', 'c']
代码没有删除最后一个字母(即“c”),字母“o”、“t”、“p”和“c”没有显示Now checking输出。
我尝试删除一些行然后就跑了 -
phrase = "Don't panic"
pList = list(phrase)
print(pList)
wanted = ["o","n","t","a","p"]
for anything in pList:
print("Now checking", anything)
这一次的输出有意义 -
Now checking D
Now checking o
Now checking n
Now checking '
Now checking t
Now checking
Now checking p
Now checking a
Now checking n
Now checking i
Now checking c
那么为什么在运行完整代码时不会发生这种情况?
【问题讨论】:
-
永远不要更改您正在迭代的列表 (
pList)! (除非你真的知道自己在做什么)。 -
您在迭代列表时正在编辑它。
-
所以这大概就是我遇到这个错误的原因吧?
-
肯定是;这可能会有所帮助:stackoverflow.com/questions/1207406/…
标签: python list for-loop python-3.6