Remove Empty Nested Lists - Python
Solution 1:
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
Solution 2:
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]
Solution 3:
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.
Solution 4:
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# ...withopen('Scores.csv', 'r') as scores:
reader = csv.reader(scores)
tscores = [[str(e) for e in r] for r in reader iflen(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.
Solution 5:
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
.
Post a Comment for "Remove Empty Nested Lists - Python"