【发布时间】:2023-04-02 16:05:02
【问题描述】:
我写了一个简单的函数来练习集合方法。有人可以告诉我为什么会出现此错误以及如何解决吗?非常感谢
n = int(input())
s = set(map(int, input().split()))
N=int(input())
for i in range(N):
inputlist=input()
if len(inputlist)==3:
s.pop()
else:
newl=inputlist.split()
comand=newl[0]
val=int(newl[1])
if comand=='remove':
s.remove(val)
else:
s.discard(val)
--------------------------------------------------------------------------------------
"my input:"
3
1 2 3
2
pop
remove 1
KeyError Traceback (most recent call last)
<ipython-input-25-6ab5ebb8e508> in <module>
11 val=int(newl[1])
12 if comand=='remove':
---> 13 s.remove(val)
14 else:
15 s.discard(val)
KeyError: 1
【问题讨论】:
标签: python if-statement input types keyerror