You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python拆分整数列表时pop()方法转移元素后未正常移除原元素问题

问题根因

你遇到的问题核心是遍历列表的同时修改列表长度:Python的for循环遍历列表时,会按索引顺序依次读取元素,你每调用一次pop(i),列表中位于i之后的所有元素索引都会自动减1,下一轮for循环会读取下一个索引的元素,就会直接跳过原本排在i后一位的元素,最终导致部分元素没被处理、残留在原列表中。

修复方案

方案1:while循环弹出队首(保留元素原有顺序)

每次直接取出原列表第一个元素处理,处理完成后原列表自然为空:

K = [15, -10, 9, 16, 7, -99, 27, 4001, 305]
single = []
multi = []

while K:
    num = K.pop(0)
    if num > 9 or num < -9:
        multi.append(num)
    else:
        single.append(num)

print(single)
print(multi)
print(K)

运行输出:

[9, 7]
[15, -10, 16, -99, 27, 4001, 305]
[]

方案2:倒序遍历索引弹出(性能更高)

从列表末尾开始处理元素,弹出末尾元素不会影响未处理的前序元素索引,时间复杂度更低:

K = [15, -10, 9, 16, 7, -99, 27, 4001, 305]
single = []
multi = []

for i in range(len(K)-1, -1, -1):
    num = K[i]
    if num > 9 or num < -9:
        multi.append(num)
    else:
        single.append(num)
    K.pop(i)

# 若需要保留元素原有顺序,可新增以下两行
# single.reverse()
# multi.reverse()

print(single)
print(multi)
print(K)

运行输出(未反转的情况):

[7, 9]
[305, 4001, 27, -99, 16, -10, 15]
[]

内容的提问来源于stack exchange,提问作者efran

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 02:06:07