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

Python技术问询:如何通过字典元素访问字典获取机场信息

关于Python字典访问与遍历的实现确认及优化建议

你的核心实现思路是没问题的,但咱们可以拆解细节,看看怎么让代码更健壮、更符合Python风格:

1. 当前代码的正确性

你用Airport.airportDict.get(itinerary[i])来获取对应机场信息的方式是合法的,前提是:

  • airportDict是Airport类的类属性(也就是定义在类里,没有绑定到实例的self上);
  • itinerary列表中的元素确实是airportDict的有效键。

dict.get()方法的好处是,当键不存在时不会抛出KeyError,而是返回None,这在遍历不确定内容的列表时,能避免程序直接崩溃,安全性更高。

2. 遍历方式的优化

Python里不推荐用range(len(itinerary)-1)这种“索引式遍历”,可以换成更简洁易读的写法:

方式一:用zip遍历相邻元素

如果你的逻辑需要同时处理当前机场和下一个机场(从变量名i的范围len(itinerary)-1推测),可以直接用zip配对相邻元素:

for current_code, next_code in zip(itinerary, itinerary[1:]):
    a1 = Airport.airportDict.get(current_code)
    # 这里可以处理当前机场a1和下一个机场的逻辑

方式二:用enumerate(保留索引)

如果确实需要用到索引,用enumerate更清晰:

for idx, current_code in enumerate(itinerary[:-1]):
    next_code = itinerary[idx+1]
    a1 = Airport.airportDict.get(current_code)

3. 关键注意事项

  • 确认字典的作用域:如果airportDict是Airport类的实例属性(定义为self.airportDict),那你直接用Airport.airportDict会报错,需要先实例化类:
    airport_instance = Airport()
    a1 = airport_instance.airportDict.get(current_code)
    
  • 处理无效机场代码:如果itinerary里可能存在无效的代码,记得对get()返回的None做处理,避免后续逻辑出错:
    a1 = Airport.airportDict.get(current_code)
    if a1 is None:
        print(f"警告:未找到机场代码 {current_code} 的信息")
        continue  # 跳过当前元素,继续遍历
    # 正常处理a1的逻辑
    
  • 直接访问vsget()的选择:如果你能保证itinerary里的所有代码都一定存在于airportDict中,也可以直接用Airport.airportDict[current_code]——这样当出现异常键时会直接抛出KeyError,能帮你快速定位数据问题。

4. 结合你之前的图构建代码

如果要把机场信息整合到之前的加权图里,可以这样优化:

graph = {}
for code in airportInput:
    airport_info = Airport.airportDict.get(code)
    if airport_info:
        graph[code] = {"airport_info": airport_info, "connections": {}}
    else:
        print(f"机场代码 {code} 不存在,已跳过")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 08:49:23