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

Python操作deque对象时pop()方法未执行、元素未移除问题求助

问题排查结果

错误根因

代码的命令执行逻辑缩进错误:所有命令判断分支都被包含在len(inp)!=1的分支内,只有带参数的append、appendleft命令会被触发执行;pop、popleft这类无参数的命令匹配到len(inp)==1分支后,没有对应执行逻辑,相当于未生效的空操作,因此deque的末尾元素不会被移除。

修复后代码

from collections import deque
N=int(input())
s=deque()
for i in range(N):
    inp=input().split()
    if len(inp)==1:
        comand = inp[0]
    else :
        comand=inp[0]
        element=inp[1]
    
    # 命令判断逻辑提至外层,与长度判断分支同级
    if comand=='append':
        s.append(element)
    elif comand=='appendleft':
        s.appendleft(element)
    elif comand=='pop':
        s.pop()
    else:
        s.popleft()

for i in s:
    print(i)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 01:06:00