问题:
力扣每日一题时,碰到个问题,在把字符插入进list,边遍历便插入的方式会出现问题,因为插入list已经改变了原本的逻辑顺序,但是在for循环的遍历过程中使用的还是原本list的性质。
解决方法:
使用一个新的list记录下你在原list要插入的位置,然后遍历新list插入原list,位置为新list元素+自身的序号。
例子:
#要插入的字符是l
s = ['l', 'x', 'f', 'b'] #原list
location = [2, 3] #插入的位置
for i in range(len(location)):
s.insert(location[i]+i,'l')
结果
['l', 'x', 'l', 'f', 'l', 'b', 'l']