mhn
mhn

Reputation: 2750

Split csv(not uniform) into 2 lists

I have a CSV with data in the format

1,2,3,4,A
2,3,B
1,4,5,6,C
5,D

and so on. How do i split it and assign each to python lists. The length of each line in csv is arbitrary. I need to split them into

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

and the rest into a python list

['A','B','C','D']

What is an efficient way to get this done. The below code is good enough to convert csv into list of lists but with the last elements. I want the last elements in a separate list

with open('dataset.csv', 'r') as fp:
  reader = csvreader(fp)
  li = list(reader)

Upvotes: 1

Views: 153

Answers (2)

efirvida
efirvida

Reputation: 4855

Try this:

import csv

with open('test.csv') as csvfile:
    readCSV = csv.reader(csvfile, delimiter=',', skipinitialspace=True)
    list1 = []
    list2 = []
    for row in readCSV:
        list1.append(row[:-1])
        list2.append(row[-1])
print list1
print list2

Upvotes: 0

Moses Koledoye
Moses Koledoye

Reputation: 78546

You can iterate through the reader object and split/unpack the items into all items excluding the last and last item.

with open('dataset.csv', 'r') as fp:
  reader = csv.reader(fp)
  lst1, lst2 = [], []
  for row in reader:
      *others, last = row # Python 2: others, last = row[:-1], row[-1]
      lst1.append(others)
      lst2.append(last)

Upvotes: 4

Related Questions