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

Python实现地点列表与对应温度输入及关联展示问题

问题解决:地点与温度的对应输入与展示

你的代码存在几个关键问题:

  1. 错误调用append方法:你尝试对temp(输入转换后的整数)调用append,但整数类型没有这个方法——你需要先创建一个专门存储温度的列表,比如temperatures = [],再往这个列表里添加温度值。
  2. 未遍历所有地点:你固定使用places[0]来获取地点,只会一直询问第一个地点的温度,需要循环遍历places列表中的每个元素。
  3. 变量逻辑混乱:重复使用count变量会导致第二个循环的计数错误,且存在拼写错误maks_temp(应为max_temp)。

修正方案1:使用两个列表对应存储

这种方式保持地点和温度的索引对应,逻辑直观:

places = []
max_places = 7

# 第一步:输入7个地点
for _ in range(max_places):
    new_place = input("Hi. Write a place to add to the list: ")
    places.append(new_place)

print(f"The 7 places are {places}")

# 第二步:为每个地点输入对应温度
temperatures = []
for place in places:
    # 确保输入转换为整数,可根据需求添加异常处理
    temp = int(input(f"What is the temperature in {place}? "))
    temperatures.append(temp)

# 输出一一对应的结果
print("\n地点与温度对应列表:")
for place, temp in zip(places, temperatures):
    print(f"- {place}: {temp}°")

修正方案2:使用字典(更推荐)

字典的键值对可以直接关联地点和温度,无需依赖索引,逻辑更清晰:

place_temperature_map = {}
max_places = 7

# 一次性输入地点和对应温度
for _ in range(max_places):
    place = input("Hi. Write a place: ")
    temp = int(input(f"What is the temperature in {place}? "))
    place_temperature_map[place] = temp

# 输出结果
print("\n地点与温度对应列表:")
for place, temp in place_temperature_map.items():
    print(f"- {place}: {temp}°")

额外说明

  • 两种方案都用for循环替代了while循环,避免了count变量带来的逻辑混乱,代码更简洁易读。
  • 如果需要处理非整数温度(比如小数),可以把int()改成float()。
  • 可以添加异常处理逻辑(比如try-except),防止用户输入非数字导致程序崩溃。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 20:20:26