在python中向集合添加项

2024-04-20 06:21:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我想创建一组卷号的学生 所以我输入学生总数,然后输入每个卷号

代码如下:

a=int(input())
s1=set()
for i in range(0,a):
  num=int(input())
  s1.add(num)

但是当我运行代码和输入值时,我得到了这个错误

9

1 2 3 4 5 6 7 8 9

Traceback (most recent call last):
  File "C:\Users\vepul\eclipse-workspace\demo\dash.py", line 4, in <module>
    num=int(input())
ValueError: invalid literal for int() with base 10: '1 2 3 4 5 6 7 8 9'

Tags: 代码inaddmostforinput错误range
1条回答
网友
1楼 · 发布于 2024-04-20 06:21:39

您要求您的代码int()字符串"1 2 3 4 5 6 7 8 9"。你知道吗

这不起作用,因为数字之间有空格,这意味着它不能转换为整数。你知道吗

当它要求输入时,您需要输入一个整数,而不是全部整数。 它将循环(在本例中为10次)以请求一个数字;每次都需要输入一个整数。你知道吗

如果您希望将所有9个整数加在一中,请尝试以下操作:

s1 = set(map(int, input().split())) ## Make sure you enter the integers space-separated

相关问题 更多 >