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

从CSV提取Name列列表失败,countries_all输出为空求助

问题与修复方案

原问题

编写Python代码意图从指定CSV文件提取Name列所有国家名称存入countries_all列表并打印,但运行后该列表为空。代码同时包含筛选特定区域内人口净增长(Net Change)为正的国家的逻辑,原代码如下:

import csv
import math


def main(file_name, region):
    
    
    min_country = None
    max_country = None
    min_population = math.inf
    max_population = -math.inf
    
    total_pop = 0
    total_countries = 0
    total_squared_diff = 0
    num_countries = 0
    
    density_pop = {}
    
    countries_all = []

    
    with open(file_name, 'r') as file:
        countries = [row for row in csv.DictReader(file) if row['Regions'] == region and float(row['Net Change']) > 0]    #Reads the CSV file and finds a list of countries in a specific region with positive net change in population
        inline = csv.DictReader(file)
        for row in file:
            columns = row.strip().split(',')
            countries_all = columns[0]
            
        print(countries_all)

错误原因

  1. 文件指针耗尽:第一次用csv.DictReader(file)遍历后,文件指针已移动到文件末尾,后续读取file不会返回任何内容。
  2. 列表赋值错误:直接将countries_all = columns[0]覆盖列表,而非用append添加元素,即便有数据也只会保留最后一行的第一个字段,且未跳过表头。
  3. 手动解析CSV不可靠:用split(',')分割CSV无法处理字段含逗号的情况,容易导致列索引错误。

修复后的代码

import csv
import math


def main(file_name, region):
    min_country = None
    max_country = None
    min_population = math.inf
    max_population = -math.inf
    
    total_pop = 0
    total_countries = 0
    total_squared_diff = 0
    num_countries = 0
    
    density_pop = {}
    
    countries_all = []
    filtered_countries = []

    with open(file_name, 'r') as file:
        reader = csv.DictReader(file)
        # 一次遍历完成两个任务:提取所有国家、筛选目标国家
        for row in reader:
            # 将Name列内容添加到countries_all列表
            countries_all.append(row['Name'])
            
            # 筛选特定区域且净增长为正的国家
            if row['Regions'] == region and float(row['Net Change']) > 0:
                filtered_countries.append(row)
        
        print("所有国家名称:")
        print(countries_all)
        print("\n指定区域内人口净增长为正的国家:")
        print(filtered_countries)

修复说明

  • 仅创建一次csv.DictReader,遍历所有行同时完成两个逻辑,避免文件指针耗尽问题。
  • 使用append方法向countries_all列表添加元素,保证所有国家名称都被存入。
  • 依赖csv.DictReader正确解析CSV字段,避免手动分割导致的错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 14:52:57