Python List -- ValueError: 以 10 为基数的 int() 无效文字: ' ' [duplicate]

Python List -- ValueError: invalid literal for int() with base 10: ' ' [duplicate]

提问人:Rajesh 提问时间:9/11/2023 更新时间:9/11/2023 访问量:83

问:

我尝试使用这两个循环以及列表理解。即使我尝试将列表中的数字转换为整数,两者都无法解析整数。

student_scores = input("Input a list of student scores.")
print(student_scores)
for n in range(0, len(student_scores)):
    student_scores[n] = int(student_scores[n])
print(student_scores)


student_score = [int(i) for i in student_scores]

highest_score = 0
for score in student_score:
    if score > highest_score:
        highest_score = score
print(f"The highest score in the class is {highest_score}")
字符串 列表 整数 列表推导式

评论

0赞 Mohammed almalki 9/11/2023
您输入此代码的值是什么?

答:

0赞 Rajesh 9/11/2023 #1

我在输入问题的末尾添加了 .split() 并能够解决问题。谢谢回复

2赞 richard 9/11/2023 #2

默认情况下,您永远不会分离作为字符串的输入。你的分隔符是什么?

student_scores = input("Input a list of student scores.")
student_scores = student_scores.split(',') if ',' in student_scores else student_scores.split()
student_scores = list(map(int, student_scores))
print(student_scores)

highest_score = max(student_scores)
print(f"The highest score in the class is {highest_score}")