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
source share