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

Python循环逻辑问题:如何遍历城市温度数据求各城市最高温

修正代码实现城市最高温度统计

你的代码存在几个关键问题,导致无法得到预期结果,以下是修正后的代码:

current_city = None
current_max = None

for line in lines:
    city, temp = line.split(',')
    temp = int(temp)
    
    if city == current_city:
        # 当前城市温度更高时更新最大值
        if temp > current_max:
            current_max = temp
    else:
        # 切换城市时,先打印上一个城市的结果(如果不是第一个城市)
        if current_city is not None:
            print(current_city, current_max)
        # 初始化新城市的最大值
        current_city = city
        current_max = temp

# 打印最后一个城市的结果
print(current_city, current_max)

原代码的问题分析:

  • 赋值错误:current_max == temp是比较运算符,不是赋值操作,应该改为current_max = temp
  • 初始值不合理:current_max = 0会导致如果城市温度都低于0时结果错误,改用None可以更安全地为新城市初始化温度最大值
  • 缺少城市切换时的打印逻辑:原代码仅在循环结束后打印最后一个城市的数据,没有在城市变化时输出上一个城市的统计结果
  • 新城市初始化逻辑缺失:第一次处理新城市时,没有将当前温度设为该城市的初始最大值

测试上述代码,输入你的数据集后,会得到预期输出:

PAR 31
LON 23
RIO 36
DUB 44

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 15:40:48