gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 08:10:40 25 4
gpt4 key购买 nike

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com