我希望能够将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
如果您确定每行中的项目数量是固定的,则可以使用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
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']]
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句