滑动二维列表行(如果其下有“”)

时间:2018-12-27 12:04:15

标签: python python-3.x

我有一个像这样的2D数组:

1,2,3,4

2,,,4,

1,4,,5

2,6,1,3

我需要滑动带有空格字符的元素,如下所示:

1,,,4

2,2,,4

1,4,3,5

2,6,1,3

我尝试过的事情:

 def slide(x,y):

            if x>0:

                if Board[x][y]==" ":

                    Board[x][y]=Board[x-1][y]

                    Board[x-1][y]=" "

                    return slide(x-1,y)

但是,如果最后一行没有空格,这是行不通的。

2 0“”“”“”“”

1 8“”“”“”“ 4

5 4“”“”“”“ 4

2 7“”“”“ 8 6

1 1“”“”“ 0 1 我想将列向右移动如果右边有一个空列 2 0

1 8 4

5 4 4

2 7 8 6

1 1 8 1

2 个答案:

答案 0 :(得分:1)

只需先按行然后按列进行迭代,然后交换数组的元素。请注意,如果第一行中有空格,它将与最后一个交换该元素(因为索引指定为i-1导致到-1)。

import numpy as np

lines = [['1', '2', '3', '4'],
         ['2', ' ', ' ', '4'],
         ['1', '4', ' ', '5'],
         ['2', '6', '1', '3']]

a = np.array(lines)
for j in range(a.shape[1]):
    for i in range(a.shape[0]):
        if a[i,j] == ' ':
            a[i,j] = a[i-1,j]
            a[i-1,j] = ' '
print(a)

输出

[['1' ' ' ' ' '4']
 ['2' '2' ' ' '4']
 ['1' '4' '3' '5']
 ['2' '6' '1' '3']]

答案 1 :(得分:0)

您可以使用不是空格作为键对每列进行排序,例如:

board = [['1', '2', '3', '4'],
         ['2', ' ', ' ', '4'],
         ['1', '4', ' ', '5'],
         ['2', '6', '1', '3']]


def slide(ls):
    columns = list(zip(*ls))
    result = [sorted(column, key=lambda x: not x.isspace()) for column in columns]
    rows = zip(*result)
    return [' '.join(row) for row in rows]


for line in slide(board):
    print(line)

输出

1     4
2 2   4
1 4 3 5
2 6 1 3