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

如何在数组中查找指定数据对应的记录?Python城市信息查询问题

错误原因
  • 原代码的判断条件if city in (city_array[1])仅检查输入内容是否存在于索引为1的第二条城市记录中,没有遍历所有已录入的城市数据
  • Python列表仅支持整数作为索引,你写的city_array[city]尝试用城市名字符串作为列表下标,属于非法语法,无法正常执行
查询逻辑修改方案

如果你的课程要求必须用数组存储所有城市记录,直接遍历数组匹配城市名即可,把main_program函数替换为如下代码:

def main_program():
  print("How many cities will you be entering?")
  length = int(input())
  city_array = createArray0fRecords(length)
  city_array = populateRecords(city_array)
  print("What city would you like the information about?")
  target_city = input().strip()
  # 新增遍历查询逻辑
  found = False
  for record in city_array:
      # record[0]对应每条记录的城市名
      if record[0] == target_city:
          print(f"城市名:{record[0]}")
          print(f"所属国家:{record[1]}")
          print(f"人口(百万):{record[2]}")
          print(f"主要语言:{record[3]}")
          found = True
          break
  if not found:
      print(f"未查询到名为{target_city}的城市信息")

如果你想优化查询效率,也可以在录入完成后把数据转换为以城市名为键的字典存储,查询时不需要遍历,直接通过键取值即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 17:54:00