You need to enable JavaScript to run this app. 如何使用Python基于CSV数据集操作字典并统计客流量最高的城市
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Python基于CSV数据集操作字典并统计客流量最高的城市

代码错误原因

  • 遍历CSV行时仅向cities字典中追加了城市名,完全没有存储每行的乘客数(乘客数存储在values[6]字段中)
  • 初始化的passengers字典为空,后续遍历空字典的循环不会执行,导致没有任何客流统计数据生成
  • 客流累加逻辑完全错误:既没有绑定对应城市,直接给字典执行+=操作也属于语法错误,无法完成累加

修正后代码

passengers = {}
is_first_line = True
# 遍历CSV文件
for row in open("Passengers_Analysis.csv", encoding="utf-8"):
    if is_first_line:
        is_first_line = False
        continue
    # 拆分每行字段,strip()是为了去除行尾换行符
    values = row.strip().split(",")
    city = values[3]
    # 累加对应城市的乘客数
    if city not in passengers:
        passengers[city] = 0
    passengers[city] += int(values[6])

max_city = ""
max_passengers = -1
# 遍历统计结果找最大值
for city, count in passengers.items():
    if count > max_passengers:
        max_passengers = count
        max_city = city

print("The most popular city:", max_city)
print("The number of passengers in the scheduled period:", max_passengers)

如果你的CSV存在字段内带逗号等特殊格式的情况,建议使用Python内置的csv模块读取,避免字段拆分错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.18 23:15:04