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
相关产品推荐
相关产品推荐

