You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将列表转为整数?计算学生身高平均值遇TypeError错误求助

问题排查与解答

1. 列表转整数的实现正确性

你的列表元素转整数的代码是正确的:

height = input("what is your higth\n").split()
for n in range(0, len(height)):
    height[n] = int(height[n])
print(height)

这段代码通过split()将输入字符串按空格分割为字符串列表,再通过循环逐个将元素转为整数,最终得到整数类型的身高列表,逻辑完全没问题。

2. 错误原因分析

报错TypeError: unsupported operand type(s) for +=: 'int' and 'list'的核心问题是:
在求和循环中,你写了t += height,但height是整个列表对象,而t是初始值为0的整数,整数和列表无法直接执行加法操作。正确的写法应该是累加列表中的每个循环变量i。

3. 完整修正代码(含平均值计算)

如果要完成平均值计算,完整修正后的代码如下:

height = input("what is your height\n").split()
# 转换为整数列表
for n in range(0, len(height)):
    height[n] = int(height[n])
print("转换后的身高列表:", height)

# 计算总和与平均值
total = 0
for i in height:
    total += i  # 累加每个元素而非整个列表
average = total / len(height)
print("身高平均值:", average)

额外优化建议

你可以用更简洁的写法简化代码:

  • 列表转整数用列表推导式:
    height = [int(h) for h in input("what is your height\n").split()]
    
  • 求和直接用内置函数sum():
    total = sum(height)
    average = total / len(height)
    

内容的提问来源于stack exchange,提问作者Amrassad

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 22:40:30