python - 在迭代期间在列表中插入元素

标签 python python-2.7

我需要在列表迭代期间插入元素并按以下方式进行。但我觉得它可以写得更好。这里 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/

相关文章:

python - 对于每组对 REST API 函数的调用,仅发送一封电子邮件

python pandas read_csv如何加快处理时间戳

python - if block 中不支持的操作数类型 TypeError

python 在每个索引处对数组中的所有先前值求和

python - 如何获取python中最顶层(入口)脚本的名称?

python - 为什么 np.array 上的 astype(uint) 不会更改 np.array 元素的类型?

Python FileCookieJar.save() 问题

python - Keras LSTM 保存后继续训练

python - 如何访问 Delicious API 以检索 Google 相关关键字

python - python 2.7 中的中心 str