我正在上 Stepik 的课程,有这样的任务
编写一个程序,将一行上的数字列表作为输入,并在一行中将其中多次出现的值打印到屏幕上。
为了解决这个问题,排序列表方法会很有用。
输出编号不应该重复,它们的输出顺序可以是任意的。
我的代码:
a = [int(i) for i in input()]
q = len(a)-1
c = []
a.sort()
for di in a:
b = a.count(di)
if b >= 2 and di not in c:
c.append(di)
continue
print(" ".join(map(str, c)))
在 IDE 中,一切正常,但在 stepik 上它给了我一个错误:
Error:
Traceback (most recent call last):
File "jailed_code", line 1, in <module>
a = [int(i) for i in input()]
File "jailed_code", line 1, in <listcomp>
a = [int(i) for i in input()]
ValueError: invalid literal for int() with base 10: ' '
请解释我有什么问题
一线队
一定是
解释:
例如,当您的输入中有以下数字列表时:
那么函数
input()
返回的不是一个列表,而是一个字符串在列表生成器中
迭代单个字符- 即 变量
i
逐渐取值"1"
,,"3"
," "
- 这里是错误函数不能将空格转换为数字
int()
!另一方面,可以
["13", "2", "7", "2"]
使用split()
.