将CSV列转换为列表 [英] Convert CSV column to list
问题描述
说我有一个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.csv
和bac.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屋!