简体   繁体   English

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

[英]Insert Element in list during iteration

I need to insert element during iteration of list and did in following way. 我需要在列表迭代期间插入元素,并按以下方式进行。 But I feel it can be written in better. 但是我觉得可以写得更好。 Here B's dictionary which contain A element Length 这是B的字典,其中包含A元素

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

I would do something like: 我会做类似的事情:

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

Assuming I've correctly understood what you're trying to achieve. 假设我已经正确理解了您要实现的目标。

iterate over the list in reverse so you don't have to worry about changes at the end of the list 反向遍历列表,因此您不必担心列表末尾的更改

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