首页 > 解决方案 > 我正在尝试将字符串列表转换为整数,但出现以下错误

问题描述

student_heights = input("Input a list of student heights ").split()
print(student_heights)

student_heights = list(map(float, student_heights))
print(student_heights)
for n in range(0, len(student_heights)):
  student_heights[n] = int(student_heights[n])

for i in student_heights:
  total = student_heights + i

for student in student_heights:
  num = student + 1

avg = total/num
Input a list of student heights 5,6,73
['5,6,73']
Traceback (most recent call last):
  File "main.py", line 5, in <module>
    student_heights = list(map(float, student_heights))
ValueError: could not convert string to float: '5,6,73'

标签: python

解决方案


看起来您正在输入逗号分隔值的列表。但是str.split()(没有参数)在空格上分裂。因此,","作为参数传递split给以逗号分隔。

而不是map将您的值 ping 到float,然后intfor循环中强制转换为,map直接到int.

而不是在循环中计算totaland ,而是使用and 。numforsumlen

(值得注意的是:num如果您希望它计算有多少学生,那么您的计算代码是不正确的。您能找出原因吗?)

例如:

student_heights = input("Input a list of student heights ").split(",")
student_heights = list(map(int, student_heights))

total, num = sum(student_heights), len(student_heights)
avg = total/num

后记:哪个学生“73”高?


推荐阅读