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

Python代码报错:'int' object is not iterable 问题排查与实现

错误排查与代码修正

核心错误点

  • 列表被覆盖为整数:altura_grupo初始定义为列表,但循环内被赋值为单个整数int(input(...)),导致后续min()/max()调用时传入非可迭代对象,触发TypeError: 'int' object is not iterable。
  • 函数名拼写错误:所有lens()均为错误写法,Python获取序列长度的正确函数是len()。
  • format()语法错误:占位符内额外添加大括号(如format({min(...)})),这会将值包装成集合,属于冗余且错误的写法,直接传入计算结果即可。
  • 百分比差值逻辑错误:原代码未基于总人数计算百分比,正确逻辑应为「男女数量差的绝对值 ÷ 总人数 × 100」。
  • 除以0风险:当群体中无女性时,计算平均身高会触发ZeroDivisionError,需添加判断规避。

修正后的完整代码

sizegroup = int(input('Digite o tamanho do grupo:'))

altura_grupo = []
altura_h = []
altura_m = []
grupo_homens = []
grupo_mulheres = []

for num in range(sizegroup):
    sexo = input('Sexo (M | F):').strip().upper()
    # 修正:将身高追加到列表,而非覆盖列表
    altura = int(input('Digite a sua altura (em cm):'))
    altura_grupo.append(altura)
    
    if sexo == 'M':
        grupo_homens.append(sexo)
        altura_h.append(altura)
    elif sexo == 'F':
        grupo_mulheres.append(sexo)
        altura_m.append(altura)
    else:
        print("Sexo inválido, ignorando este registro.")

# 展示最小和最大身高
if altura_grupo:
    print('A menor e maior altura do grupo são: {} e {}'.format(min(altura_grupo), max(altura_grupo)))
else:
    print("Nenhuma altura registrada.")

# 计算女性平均身高
if grupo_mulheres:
    media_feminina = sum(altura_m) / len(grupo_mulheres)
    print(f'A média das alturas femininas é: {media_feminina:.2f} cm')
else:
    print("Não há mulheres no grupo, não é possível calcular a média.")

# 计算男女数量的百分比差值
total_homens = len(grupo_homens)
total_mulheres = len(grupo_mulheres)
if sizegroup > 0:
    diferenca_percentual = (abs(total_homens - total_mulheres) / sizegroup) * 100
    print(f'A quantidade de homens é {total_homens} e a diferença percentual com a quantidade de mulheres é de: {diferenca_percentual:.2f}%')
else:
    print("Grupo vazio, não há diferença percentual.")

额外优化说明

  • 对性别输入做strip().upper()处理,避免大小写、空格导致的判断错误。
  • 添加无效性别输入的提示,过滤错误数据。
  • 对空列表、除以0的场景做了判断,提升代码健壮性。
  • 用f-string替代部分format()写法,让代码更简洁易读。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 23:55:22