【问题标题】:.pop() doesn't get executed for a deque object.pop() 不会为双端队列对象执行
【发布时间】:2021-10-31 00:11:22
【问题描述】:

我写了一个代码来执行多个命令。找不到原因,当我输入pop,并打印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)

【问题讨论】:

  • 您能否提供一系列命令来重现您声称看到的行为? pop 对我来说很好。
  • 2 append 50 pop deque(['50'])
  • 对,我忘了我用pop 2 测试过,以为命令必须有一个虚拟的第二个元素。但这会导致问题:你的缩进。

标签: python list collections coding-style deque


【解决方案1】:

处理执行的if 语句是缩进的,因此它是else 子句的一部分。您的任何单元素命令都不起作用; if 语句需要取消缩进,以便它始终在定义 comand 和(可能)element 之后运行。

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()
    elif comand == 'popleft':
        s.popleft()
    else:
        print(f"Unrecognized command {comand}")

【讨论】:

  • 非常感谢!现在我明白了,我花了 10 分钟写代码,30 分钟理解我的错误,还有很多东西要学!对不起,我没有足够的声誉来支持你
猜你喜欢
  • 2011-08-12
  • 1970-01-01
  • 2014-06-01
  • 2018-07-02
  • 2012-07-27
  • 1970-01-01
  • 2016-10-20
  • 2015-02-02
  • 2020-04-19
相关资源
最近更新 更多