Python在循环中修改遍历的字符串

  • 举例展示

Python在循环中修改遍历的字符串,将不会影响循环的遍历顺序和执行轮数

astr = "abcaef"
bstr = "bcef"
for i in astr:
    if i not in bstr:
        astr = astr.replace(i,'')
        print(i)

如上示例代码中,当i=='a'时,bstr中没有'a',输出'a'并将astr中的所有'a'去掉;

但后续遍历时依然会遍历原字符串astr,于是我们得到代码执行输出两次'a'

  • 原因分析

字符串在Python中属于不可变类型

for...in...的迭代实际是将可迭代对象转换成迭代器,再重复调用next()方法实现的

  • 对比说明

在python中,可变对象(列表、字典)在迭代时会发生变化,甚至导致错乱,如:

lst = [1, 2, 3, 4, 5]
for x in lst:
    if x%2==0:
        lst.remove(x) #remove,insert等操作
print(lst)

解决方法:创建一个浅拷贝

lst = [1, 2, 3, 4, 5]
for x in lst[:]:   #注意此处修改
    if x%2==0:
        lst.remove(x) #remove,insert等操作
print(lst)

得到正常的输出>>>[1, 3, 5]

 

posted on 2023-06-07 17:47  shui00cc  阅读(287)  评论(0)    收藏  举报