在2048中进行移位功能 [英] Making a shift function in 2048

查看:57
本文介绍了在2048中进行移位功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们说我有一个清单:

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

所以我有办法从每行中删除每个0并将其添加回末尾(即使列表中有不同的值),这样板子现在看起来像:

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

第1行的代码为:

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]

推荐答案

您可以使用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]

输出:

[2, 4, 2, 0, 8, 4, 4, 8, 2, 0, 0, 0, 4, 2, 2, 0]

这篇关于在2048中进行移位功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆