Hackerrank显示IndexError:从python中的空列表中弹出



我正在使用pop函数从列表中删除一个值。在pyCharm中,我的代码运行良好。但是当我尝试在 Hackerrank 上运行它时,它向我展示了IndexError: pop from empty list

我试过这个:

list = [] //this is the list which I declare.
elif e == 'pop': //this is the else if condition which is needed.
list.pop()

这是我的代码

n = int(input())
list = []
for i in range(1,n+1):
e = input()
if e == 'insert':
j = int(input())
k = int(input())
list.insert(j,k)
elif e == 'print':
print(list)
elif e == 'remove':
j = int(input())
list.remove(j)
elif e == 'append':
j = int(input())
list.append(j)
elif e == 'sort':
list.sort()
elif e == 'pop':
list.pop()
elif e == 'reverse':
list.reverse()

我期待输出

[6, 5, 10]
[1, 5, 9, 10]
[9, 5, 1]

可能需要在pop之前检查列表是否为空。如果列表为空,则没有元素可以pop。您可以使用len进行检查。

当您尝试在空listpop()时会发生这种情况
它适用于您的本地计算机,并且不会在Hackerrank上运行,因为它们的测试用例。
他们有隐藏的测试用例,他们正在空列表中测试pop()功能。

在代码中添加一个简单的验证,同时从列表中弹出元素。


if e == 'pop':
if list:
list.pop()

if list:基本上检查列表是否为空。
如果列表为空,则返回False,反之亦然。

最新更新