如何将csv文件转换为python中的列表列表

Kyu*_*yuu 3 python csv list

我希望能够将csv文件转换为列表列表,其中包含每个列表的列值.例如:

6,2,4
5,2,3
7,3,6
Run Code Online (Sandbox Code Playgroud)

[[6,5,7],[2,2,3],[4,3,6]]
Run Code Online (Sandbox Code Playgroud)

我只是设法打开文件,只有成功打印成行

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

        header = csv_file.next() 

        raw_data = csv_file
Run Code Online (Sandbox Code Playgroud)

Mik*_*mov 8

如果您确定每行中固定数量的项目,您可以使用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')]
Run Code Online (Sandbox Code Playgroud)

或者如果行中的项目数不同:

6,2,4
5,2
7
Run Code Online (Sandbox Code Playgroud)

使用zip_longest过滤器:

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']]
Run Code Online (Sandbox Code Playgroud)