将CSV列转换为列表 [英] Convert CSV column to list

查看:844
本文介绍了将CSV列转换为列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有一个CSV文件. 它包含:

Say I have a CSV file. It contains:

a,b,c
1,2,3
4,5,6
7,8,9

如何在不对行进行硬编码的情况下将标记为"a"的列转换为列表?

How can I turn the column labeled 'a' into a list, without hard-coding a row to it?

最初,我在第一行a,b,c上进行了读取行,然后将行硬编码到每个变量中.但是后来我想到:如果我想这样做,而又可能是CSV文件的排列方式不一样-说:

Originally, I was doing a readline for the first line a,b,c and then hard-coding a row to each variable. But then I thought: what if I wanted to do it with the possibility of the CSV file not being arranged the same way - say:

b,a,c
2,1,3
5,4,6
8,7,9

解决此问题的最佳方法是什么?

What's the best way to go about this?

推荐答案

csv.DictReader 将CSV文件的每一行转换为字典,并以列标题为键.对于您的情况(假设问题中的两个示例分别命名为abc.csvbac.csv),可以这样使用:

csv.DictReader turns each row of your CSV file into a dictionary with the column headers as keys. For your case (assuming the two examples in your question are named abc.csv and bac.csv respectively), you could use it like this:

from csv import DictReader

with open("abc.csv") as f:
    a1 = [row["a"] for row in DictReader(f)]

with open("bac.csv") as f:
    a2 = [row["a"] for row in DictReader(f)]

# a1 == a2 == ['1', '4', '7']

这篇关于将CSV列转换为列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆