python - 我正在尝试将字符串列表转换为整数,但出现以下错误
问题描述
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'
解决方案
看起来您正在输入逗号分隔值的列表。但是str.split()
(没有参数)在空格上分裂。因此,","
作为参数传递split
给以逗号分隔。
而不是map
将您的值 ping 到float
,然后int
在for
循环中强制转换为,map
直接到int
.
而不是在循环中计算total
and ,而是使用and 。num
for
sum
len
(值得注意的是: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”高?
推荐阅读
- python - 根据另一个列条件将列表替换为数据框中的另一个列表
- python - 当我的函数 A 只需要在 B 中运行时,如何将它作为函数 B 的参数?(Python)
- android - 为什么我的应用程序的某些部分在一个上下文中工作而在另一个上下文中不工作?
- c# - 创建正则表达式以删除除换行符以外的连续空格
- apache-flink - 如何使用 Flink SQL 按事件时间对流进行排序
- android - 在颤振应用程序的android本机模块中使用mapbox导航api时资源链接失败
- php - 如何对 PHP 生成的 HTML 表的每个字段执行计算?
- java - 如何修复此 Java 代码以使其不仅适用于 A 的所有等级?
- jakarta-ee - 在任何地方都找不到 JSTL 1.2 官方规范的链接
- angular - 如何在 ng-select 中的 Observable 类型的数组中插入值