繁体   English   中英

在迭代过程中将元素插入列表

[英]Insert Element in list during iteration

我需要在列表迭代期间插入元素,并按以下方式进行。 但是我觉得可以写得更好。 这是B的字典,其中包含A元素

_leftcell = leftcell[:]
index = 1
for A in leftcell:
    if B[A].length  % 140 != 0:
        _leftcell.insert(index, 2)
        index +=2
leftcell= _leftcell[:]

我会做类似的事情:

for item in leftcell[:]:
    if B[item].length % 140:
        leftcell.insert(leftcell.index(item), 2)

假设我已经正确理解了您要实现的目标。

反向遍历列表,因此您不必担心列表末尾的更改

left_len = len(leftcell)
for i in xrange(left_len-1,0,-1):
    if B[leftcell[i]].length  % 140 != 0:
        leftcell.insert(i, 2)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM