将.csv文件的每一列解析为单个列表python

时间:2017-05-10 18:40:19

标签: python csv python-2.4

我有以下类型的csv

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

我想将此csv文件的每一列解析为包含out列的列表,因此最终结果将是

myList = ["1","4","7","2","5","8","3","6","9"]

我找到了一个列的许多解决方案,但我需要灵活,能够读取文件的每一列。我正在使用旧版本的python,因此我无法使用任何带有pandas库的解决方案。

3 个答案:

答案 0 :(得分:4)

您可以完全读取文件,然后zip行转置它们,然后将结果链接以展平列表。独立示例(使用字符串列表作为输入):

import csv,itertools

text="""a,b,c
1,2,3
4,5,6
7,8,9
""".splitlines()

myList = list(itertools.chain.from_iterable(zip(*csv.reader(text[1:]))))

print(myList)

结果:

['1', '4', '7', '2', '5', '8', '3', '6', '9']
从文件中读取

with open("test.csv") as f:
    cr = csv.reader(f,separator=",")  # comma is by default, but just in case...
    next(cr)  # skip title
    myList = list(itertools.chain.from_iterable(zip(*cr)))

答案 1 :(得分:0)

简单方法:

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

cells = []
for line in d.split("\n"):
    if line:
        cells.append(line.strip().split(','))

print(cells)

for n in range(len(cells[0])):
    for r in cells:
        print(r[n]) 

相同的迭代,但作为生成器:

def mix(t):
    for n in range(len(t[0])):
        for r in t:
            yield r[n]

print( list( mix(cells) )  )

答案 2 :(得分:0)

使用csvchain展平列表

import csv
from itertools import chain

l = list(csv.reader(open('text.csv', 'r')))
mylist = map(list, zip(*l[1:])) # transpose list
list(chain.from_iterable(mylist)) # output ['1', '4', '7', '2', '5', '8', '3', '6', '9']