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

使用Python的for循环与条件语句拆分温度列表遇阻求助

温度列表分类问题解决

你的代码存在几个关键问题,以下是问题点和修正方案:

问题分析

  • 语法错误:range(len(temperatures): 缺少闭合括号,正确写法是range(len(temperatures)):
  • 循环变量误用:你用i遍历的是列表的索引(0到9),而非实际温度值,导致判断的是索引大小而非温度高低
  • 缩进错误:elif分支下的temp_above_zero.append(i)未缩进,不符合Python的语法规范

修正方案

推荐直接遍历列表中的温度元素,写法更简洁直观:

temperatures = [-2, 1, 10.2, 6, 15, -6, 20, 13.5, 0.9, -8.3]
temp_below_zero = []
temp_above_zero = []

# 遍历每个温度值
for temp in temperatures:
    if temp < 0:
        temp_below_zero.append(temp)
    elif temp > 0:
        temp_above_zero.append(temp)

print("零下温度:", temp_below_zero)
print("零上温度:", temp_above_zero)

如果坚持使用索引遍历的方式,可修改原代码如下:

temperatures = [-2, 1, 10.2, 6, 15, -6, 20, 13.5, 0.9, -8.3]
temp_below_zero = []
temp_above_zero = []

# 修正语法错误,通过索引获取实际温度值
for i in range(len(temperatures)):
    current_temp = temperatures[i]
    if current_temp < 0:
        temp_below_zero.append(current_temp)
    elif current_temp > 0:
        temp_above_zero.append(current_temp)

print(temp_below_zero, temp_above_zero)

运行结果

两种写法都会输出:

零下温度: [-2, -6, -8.3]
零上温度: [1, 10.2, 6, 15, 20, 13.5, 0.9]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 09:15:31