简体   繁体   中英

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

_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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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