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

去除CSV文件重复项并合并对应数值

解决方法

我们可以用Python基础语法实现这个需求,完全不需要依赖任何外部模块或包,核心思路是用字典来聚合同一城市的数值:

  • 初始化空字典,键为城市名称,值为对应数值的列表
  • 逐行处理输入内容,拆分出城市和数值,将数值追加到对应城市的列表中
  • 最后遍历字典,按「城市 数值1,数值2...」的格式生成输出内容

代码实现

# 模拟读取输入文件内容(实际场景可替换为文件读取操作)
input_text = """Mumbai 2
Pune 6
Bangalore 8
Pune 10
Mumbai 8"""

# 初始化存储城市数据的字典
city_dict = {}

# 逐行处理输入内容
for line in input_text.splitlines():
    city, num = line.split()
    if city not in city_dict:
        city_dict[city] = []
    city_dict[city].append(num)

# 生成格式化的输出内容
output_lines = []
for city, nums in city_dict.items():
    output_lines.append(f"{city} {','.join(nums)}")

# 输出结果(实际场景可写入目标文件)
print('\n'.join(output_lines))

运行结果

执行代码后会输出:

Mumbai 2,8
Pune 6,10
Bangalore 8

如果要处理真实文件,只需调整读取和写入部分的代码:

# 读取输入文件
with open("input.txt", "r") as f:
    input_text = f.read()

# ...(中间处理逻辑不变)...

# 写入输出文件
with open("output.txt", "w") as f:
    f.write('\n'.join(output_lines))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 20:55:23