Reputation: 143
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?
Upvotes: 3
Views: 5364
Reputation: 7338
tscores = [x for x in tscores if x]
If the list is empty the conditional will return false, and therefore will not be included in tscores
.
Upvotes: 0
Reputation: 10992
Just for completeness: In such cases I think that list comprehensions are not the most simple solution. Here functional programming would make sense, imho.
To "automatically" iterate over a list and filter specific elements, you could use the built-in function filter:
In [89]: a = [ [1, 2], [], [3, 4], [], [5, 6], [], [], [9, 5, 2, 5]]
In [91]: filter(lambda x: len(x) > 0, a)
Out[91]: [[1, 2], [3, 4], [5, 6], [9, 5, 2, 5]]
Every element x
of the list a
is passed to the lambda
function and the returned list only contains an element of a
if and only if the condition len(x) > 0
is met. Therefore a list without the nested empty lists is returned.
Upvotes: 1
Reputation: 17500
I'm not sure I'm understanding your question correctly, but you can remove the empty entries from a list of lists (or a list of tuples or a list of other sequences) using something like this:
#/bin/python
# ...
with open('Scores.csv', 'r') as scores:
reader = csv.reader(scores)
tscores = [[str(e) for e in r] for r in reader if len(r)]
... remember that your list comprehension can handle optional conditional clauses for filtering. This will only work if you can ensure that every element of the list that you're traversing support the len() function (of course you can ensure this by using a more complex condition such as: hasattr(r, 'len') and len(r)
Note: this only tests one level of depth ... it is not recursive.
Upvotes: 0
Reputation: 229281
Alternative to user2990008's answer, you can not create the empty lists in the first place:
tscores = [[str(e) for e in r] for r in reader if len(r) > 0]
Upvotes: 1
Reputation: 920
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
Upvotes: 1