如何在Python中将CSV文件转换为列表?

7
我希望能够将CSV文件转换为包含每个列表的列值的二维列表。例如:
6,2,4
5,2,3
7,3,6

转换为

[[6,5,7],[2,2,3],[4,3,6]]

我只能打开这个文件,以行的形式打印它才能成功。

with open(input,'rb') as csvfile:
        csv_file = csv.reader(csvfile)

        header = csv_file.next() 

        raw_data = csv_file

2
https://dev59.com/Z2Qn5IYBdhLWcg3w36XV - msvalkon
导入 csvaList = [] with open('/Users/YYY/Desktop/Workbook1.csv', 'rU') as f: reader = csv.reader(f) for row in reader: aList.append(row) print(aList)

[['6', '2', '4'], ['5', '2', '3'], ['7', '3', '6']]

- Ark
输出需要按列排列,因此[[6,5,7],[2,2,3],[4,3,6]]。 - Kyuu
3个回答

12

如果您确定每行有固定数量的项,可以使用 zip

import csv

with open('test.csv') as csvfile:
    rows = csv.reader(csvfile)
    res = list(zip(*rows))
    print(res)
    # [('6', '5', '7'), ('2', '2', '3'), ('4', '3', '6')]

或者在行中有不同数量的项目:

6,2,4
5,2
7

使用 zip_longestfilter 函数:

import csv
from itertools import zip_longest

with open('test.txt') as csvfile:
    rows = csv.reader(csvfile)

    res = list(zip_longest(*rows))
    print(res)
    # [('6', '5', '7'), ('2', '2', None), ('4', None, None)]

    res2 = [list(filter(None.__ne__, l)) for l in res]
    print(res2)
    # [['6', '5', '7'], ['2', '2'], ['4']]

1
如果你使用的是Python2.x,可以使用itertools中的izip函数,避免将其转换为列表,除非你真的需要一个列表 :-) - izak

3
您可以先将其读入一个列表的列表中:
from csv import reader as csvreader
with open(input, 'r') as fp:
    reader = csvreader(fp)
    li = list(reader)

然后将其切割为一个新的序列,我相信itertools中有其他技巧,但这是我想到的:

from itertools import count
def my_gen():
    for i in count():
        try:
            yield [x[i] for x in li]
        except IndexError:
            break

现在你可以将生成器转换为列表,其中所需的列将作为行。

list(my_gen())

1
@germn的答案比我的更好。zip/izip基本上做了我my_gen所做的事情。 - izak

0

或者像这样...

from csv import reader   

with open('test.csv') as csv_file:
    csv_reader = reader(csv_file)
    rows = list(csv_reader)
    print(rows)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接