我需要在列表迭代期间插入元素并按以下方式进行。但我觉得它可以写得更好。这里 B 的字典包含 A 元素 Length
_leftcell = leftcell[:]
index = 1
for A in leftcell:
if B[A].length % 140 != 0:
_leftcell.insert(index, 2)
index +=2
leftcell= _leftcell[:]
最佳答案
反向遍历列表,这样您就不必担心列表末尾的变化
left_len = len(leftcell)
for i in xrange(left_len-1,0,-1):
if B[leftcell[i]].length % 140 != 0:
leftcell.insert(i, 2)
关于python - 在迭代期间在列表中插入元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23159411/