Parsing each column of a .csv file into a single python list

I have the following csv type

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

I would like to parse each column of this csv file into a list without columns so that the final result is

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

I found many solutions for one column, but I need to be flexible to read each column of the file. I am using an older version of python, so I cannot use any solutions with the pandas library.

+4
source share
3 answers

You can read the entire file, and then the ziplines to transpose them, and then combine the result to smooth the list. Standalone example (using a list of strings as input):

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)

result:

['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)))
+4

:

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) )  )
0

Using csvand chainto smooth the list

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']
0
source

Source: https://habr.com/ru/post/1676863/


All Articles