0

I have the data in the following format (in a csv file):

a b c
b
a
a c d
b c
b c

I would like to covert the above data to the following format (list):

[['a', 'b', 'c'],
 ['b'],
 ['a'],
 ['a', 'c', 'd'],
 ['b', 'c'],
 ['b', 'c']]

I have done this so far:

import csv

fileName = "toydataset.csv"

data = open(fileName, 'r')
reader = csv.reader(data)
allRows = [row for row in reader]
allRows

But, the output looks like this:

[['a', 'b', 'c'],
 ['b', '', ''],
 ['a', '', ''],
 ['a', 'c', 'd'],
 ['b', 'c', ''],
 ['b', 'c', '']]

How do I remove those null values from the list so the output looks like this?

[['a', 'b', 'c'],
 ['b'],
 ['a'],
 ['a', 'c', 'd'],
 ['b', 'c'],
 ['b', 'c']]

3 Answers 3

3
In [8]: l
Out[8]: 
[['a', 'b', 'c'],
 ['b', '', ''],
 ['a', '', ''],
 ['a', 'c', 'd'],
 ['b', 'c', ''],
 ['b', 'c', '']]

In [9]: [ filter(None, a) for a in l]
Out[9]: [['a', 'b', 'c'], ['b'], ['a'], ['a', 'c', 'd'], ['b', 'c'], ['b', 'c']]
Sign up to request clarification or add additional context in comments.

Comments

2

Here's an alternative. If you're in to that sort of thing.

import csv


def clean_item(item):
    res = [x for x in item if x]
    return res


def main():
    # PEP-8!
    file_name = "toydataset.csv"
    with open(file_name, 'r') as data: # don't corrupt your data!
        reader = csv.reader(data)
        # PEP-8!
        all_rows = [row for row in reader if row]
        print(all_rows)


if __name__ == '__main__':
    main()

Comments

0

You can also do it without using any built-in method:

>>> l
[['a', 'b', 'c'], ['b', '', ''], ['a', '', ''], ['a', 'c', 'd'], ['b', 'c', ''], ['b', 'c', '']]
>>> [[i for i in j if i] for j in l]
    [['a', 'b', 'c'], ['b'], ['a'], ['a', 'c', 'd'], ['b', 'c'], ['b', 'c']]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.