Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Push all non-'0' to front

I'm using the following (ugly) snippet to iterate over a two-dimensional list with strings. It checks whether one of the values is '0' and whether it's not the last element. If it isn't, it will switch the values of the current element (which is '0') with the value of the next element.

What I intended to accomplish with this function is to push all non-'0' values to the back. It's obviously not working as expected yet (it's a start), but I can't figure out a way to get this done without turning it into a big mess.

What's the missing piece to the puzzle? Would recursion help here?

['0', '2', '0', '4']

should turn into

['2', '4', '0', '0']

and

['0', '3', '1', '0', '2']

into

['3', '1', '2', '0', '0']  

Current snippet:

for idx, x in enumerate(self.list_x):
     for idy, i in enumerate(x):
        if i == '0':
            try:
                if x[idy+1]:
                    pass
            except IndexError:
                pass
            else:
                temp = i
                self.list_x[idx][idy] = x[idy+1]
                self.list_x[idx][idy+1] = temp
like image 578
Mast Avatar asked Sep 26 '22 11:09

Mast


1 Answers

In [63]: A = ['0', '2', '0', '4']

In [64]: B = ['0', '3', '1', '0', '2']

In [65]: [i for i in A if i!='0'] + [i for i in A if i=='0']
Out[65]: ['2', '4', '0', '0']

In [66]: [i for i in B if i!='0'] + [i for i in B if i=='0']
Out[66]: ['3', '1', '2', '0', '0']
like image 200
inspectorG4dget Avatar answered Oct 03 '22 13:10

inspectorG4dget