Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove leftmost/rightmost elements in list that satisfy a certain criterion in python? [duplicate]

Tags:

python

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]
like image 423
Julian Avatar asked Apr 20 '13 12:04

Julian


1 Answers

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?

like image 144
Lauritz V. Thaulow Avatar answered Oct 05 '22 14:10

Lauritz V. Thaulow