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
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']
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