Push all non-0 'forward

I use the following (ugly) snippet to iterate over a two-dimensional list with strings. It checks to see if one of the values ​​is '0' and whether it is the last element. If this is not the case, it will switch the values ​​of the current element (which is equal to '0' ) with the value of the next element.

What I was going to do with this function was to push all the values ​​not '0' to the back. Obviously, it does not work as expected (this is the beginning), but I cannot figure out how to do this without turning it into a big mess.

What is the missing piece of the puzzle? Can recursion help here?

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

should turn into

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

and

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

in

 ['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 
+5
source share
2 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'] 
+4
source
 In [79]: L = ['0', '2', '0', '4'] In [80]: inds = [i for i,e in enumerate(L) if e!='0'] In [81]: answer = list(operator.itemgetter(*inds)(L)) + ['0']*(len(L)-len(inds)) In [82]: answer Out[82]: ['2', '4', '0', '0'] 
0
source

Source: https://habr.com/ru/post/1233821/


All Articles