Skip to main content
 首页 » 编程设计

python之移动和合并矩阵的元素

2025年02月15日8zdz8207

How can I shift and merge elements of a matrix to have the following result ?

向右移动: [[0,0,2,2,0,2],[8,4,2,2,0,2]] ==> [[0,0,0, 0,4,2],[0,0,8,4,4,2]]

或

向左移动: [[0,0,2,2,0,2],[8,4,2,2,0,2]] ==> [[4,2,0, 0,0,0],[8,4,4,2,0,0]]

It's like the 2048 game. For example, when the user do a left move, every numbers go to the left of the list and if 2 numbers side-by-side are equals, tere is an addition of the two numbers.

我想用循环来做。

我尝试了一些我在互联网上找到的代码,但作为初学者,我没有找到一个简单的代码来理解如何做到这一点。

在此先感谢您的帮助。

请您参考如下方法:

如果我没有误解你的意思,我写了一些代码,希望这对你有帮助:

a = [[0, 0, 2, 2, 0, 2], [8, 4, 2, 2, 0, 2]] 
f = lambda x: [2 * x[0]] if x[0] == x[1] else x 
 
def move_left(l): 
    c, l = [], l + [0] if len(l) % 2 else l 
 
    for i in range(0, len(l), 2): 
        c = c + f(l[i:i + 2]) 
    c = list(filter(lambda x: x != 0, c)) 
    return c + ([0] * (len(l) - len(c))) 
 
 
def move_right(l): 
    c, l = [], l + [0] if len(l) % 2 else l 
 
    for i in range(len(l), 0, -2): 
        c = f(l[i - 2:i]) + c 
    c = list(filter(lambda x: x != 0, c)) 
    return ([0] * (len(l) - len(c))) + c 
 
for i in a: 
    print(move_left(i)) 

输出:

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

看来您使用的是 Python3.x,因此您应该使用 list(filter(lambda x: x != 0, c)) 来获取列表。