Remove empty nested lists - Python

PairedPrototype

I'm reading in a .csv file to a list and it appends an empty lists, I'm using the code below to do this.

with open('Scores.csv', 'r') as scores:
    reader = csv.reader(scores)
    tscores = [[str(e) for e in r] for r in reader]

It creates a list of nested lists correctly but appends an empty list after every row read in like so:

[[score1, name1], [], [score2, name2], []]

I believe it's reading \n as an empty string which is why I'm getting that, so I tried to remove empty lists using:

tscores = [tscores.remove(x) for x in tscores if x]

which does delete empty nested lists, but it sets all other nested lists that contained data to None i.e. [None, None]. I modified to:

tscores = [tscores.remove(x) for x in tscores if []]

which wipes out all nested lists completely.

How can I read the file with the same output (a list of nested lists) without appending empty lists or how can I remove all empty lists after being read in?

m7mdbadawy

I think what you want to do is

tscores = [x for x in tscores if x != []]

which make a list of only the none empty lists in tscores

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related