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

2024-10-08 19:19:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要在列表的迭代过程中插入元素,并按以下方式执行。但我觉得可以写得更好。这里是包含元素长度的字典

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

Tags: in元素列表forindexif字典过程
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)

我会这样做:

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

假设我正确理解了你想要达到的目标。你知道吗

相关问题 更多 >

    热门问题