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]
You can use list.count
:
board = [2, 4, 0, 2, 8, 4, 4, 8, 0, 2, 0, 0, 4, 0, 2, 2]
new_board = [board[i:i+4] for i in range(0, len(board), 4)]
final_board = [list(filter(None, i))+([0]*i.count(0)) for i in new_board]
last_board = [i for b in final_board for i in b]
Output:
[2, 4, 2, 0, 8, 4, 4, 8, 2, 0, 0, 0, 4, 2, 2, 0]
Sometimes there is nothing wrong with a simple loop:
board = [2, 4, 0, 2, 8, 4, 4, 8, 0, 2, 0, 0, 4, 0, 2, 2]
x=4
nb=[]
for e in zip(*[iter(board)]*x):
ne=[se for se in e if se!=0]
nb.extend(ne+[0]*(x-len(ne))) #.append if you want to maintain sub lists
>>> nb
[2, 4, 2, 0, 8, 4, 4, 8, 2, 0, 0, 0, 4, 2, 2, 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