Let us say i have a list:
board = [2, 4, 0, 2, 8, 4, 4, 8, 0, 2, 0, 0, 4, 0, 2, 2]
and i already have some code that will make the list be displayed like this:
2 4 0 2
8 4 4 8
0 2 0 0
4 0 2 2
So is there a way for me to remove every 0 from each row and add it back in the end(even if there are different values in the list) so that the board now looks like:
2 4 2 0
8 4 4 8
2 0 0 0
4 2 2 0
I want to do this using a loop and not individually having to write separate code for each row.
Also can you do this without making the initial list to
board = [[2, 4, 0, 2], [8, 4, 4, 8], [0, 2, 0, 0], [4, 0, 2, 2]]
The code for 1 row would be :
board = [2, 0, 0, 2]
k = len(board)
board[:] = (value for value in board if value != 0)
while len(board) < k:
board.append(0)
print(board)
Output = [2, 2, 0, 0]
Just for fun, here's a one-liner using some of Python's functional tools. The key ingredients are
functools.partial
,itertools.chain.from_iterable
, andoperator.not_
, all of which come from the Functional Programming Modules section of Python's standard library documentation.Most of the work here is in turning the linear representation of the board into a nested list-of-lists representation, and then turning it back again. Here it is step-by-step.
First, turning the flat representation into a nested one:
I've added that extra outer
list
call just to show the contents of thezip
iterable. It's not necessary once all the steps are put together. Now sort each row with a suitable key to move the zeros to the right:Again, the outer list call is unnecessary, and we'll lose it when we put everything together. A key point here is that Python's
sorted
function provides a stable sort, so the nonzero elements stay in the same order with respect to each other. Finally, flatten back into a list:Putting this all together, and removing the unnecessary inner conversions to list, you get the one liner at the top of this post.
Sometimes there is nothing wrong with a simple loop:
You can use
list.count
:Output: