I have a list that looks like this:
['a', 'b', 'c', '', '', '']
This is the result of parsing a 'dirty' csv file. I now want to get rid of the empty columns on the right. I cannot just use counting, because the length is variable. I also cannot just use simple filtering, because there are also rows that look like this:
['a1', '', 'c1', '', '']
So I have to preserve the empty columns that are not at the very right. Is there an idiomatic way to do this? I am hoping for something like a "removeWhile" function that I could apply on the reversed list.
The best I've come up with so far is the following:
def filterRow(row):
row.reverse()
blanks = 0
for x in row:
if x == '':
blanks += 1
else:
break
row.reverse()
return row[0:-blanks]
def filterRow(row):
while row[-1] == "":
row.pop()
If you don't want to do it in-place for some reason, do it like this instead:
def filterRow(row):
row = list(row)
while row[-1] == "":
row.pop()
return row
Popping off the end of a list is very fast, and though it may be slightly faster to calculate the last index and do a slice, it will also result in longer, more complicated, and harder to read code. Therefore, go with the readable version for now, and consider changing it only once you've determined it to be a significant bottleneck in practice.
To make the function even more intuitive, why not call it rstrip
instead of filterRow
, since it does almost the same thing that str.rstrip
does to strings?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With