使用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
相关产品推荐
相关产品推荐

