获取二维列表列中非空项的距离

时间:2016-10-16 12:42:55

标签: python python-3.x multidimensional-array distance

我正在尝试制作一个拼字游戏。我有一个董事会,定义如下。

self.board = [[" ", "A ", "B ", "C ", "D ", "E ", "F ", "G ", "H ", "I ", "J ", "K ", "L ", "M ", "N ", "O "],
    ['01', 'TWS', ' ', ' ', 'DLS', ' ', ' ', ' ', 'TWS', ' ', ' ', ' ', 'DLS', ' ', ' ', 'TWS'],
    ['02', ' ', 'DWS', ' ', ' ', ' ', 'TLS', ' ', ' ', ' ', 'TLS', ' ', ' ', ' ', 'DWS', ' '],
    ['03', ' ', ' ', 'DWS', ' ', ' ', ' ', 'DLS', ' ', 'DLS', ' ', ' ', ' ', 'DWS', ' ', ' '],
    ['04', 'DLS', ' ', ' ', 'DWS', ' ', ' ', ' ', 'DLS', ' ', ' ', ' ', 'DWS', ' ', ' ', 'DLS'],
    ['05', ' ', ' ', ' ', ' ', 'DWS', ' ', ' ', ' ', ' ', ' ', 'DWS', ' ', ' ', ' ', ' '],
    ['06', ' ', 'TLS', ' ', ' ', ' ', 'TLS', ' ', ' ', ' ', 'TLS', ' ', ' ', ' ', 'TLS', ' '],
    ['07', ' ', ' ', 'DLS', ' ', ' ', ' ', 'DLS', ' ', 'DLS', ' ', ' ', ' ', 'DLS', ' ', ' '],
    ['08', 'TWS', ' ', ' ', 'DLS', ' ', ' ', ' ', 'B', 'O', 'G', ' ', 'DLS', ' ', ' ', 'TWS'],
    ['09', ' ', ' ', 'DLS', ' ', ' ', ' ', 'DLS', ' ', 'DLS', ' ', ' ', ' ', 'DLS', ' ', ' '],
    ['10', ' ', 'TLS', ' ', ' ', ' ', 'TLS', ' ', ' ', ' ', 'TLS', ' ', ' ', ' ', 'TLS', ' '],
    ['11', ' ', ' ', ' ', ' ', 'DWS', ' ', ' ', ' ', ' ', ' ', 'DWS', ' ', ' ', ' ', ' '],
    ['12', 'DLS', ' ', ' ', 'DWS', ' ', ' ', ' ', 'DLS', ' ', ' ', ' ', 'DWS', ' ', ' ', 'DLS'],
    ['13', ' ', ' ', 'DWS', ' ', ' ', ' ', 'DLS', ' ', 'DLS', ' ', ' ', ' ', 'DWS', ' ', ' '],
    ['14', ' ', 'DWS', ' ', ' ', ' ', 'TLS', ' ', ' ', ' ', 'TLS', ' ', ' ', ' ', 'DWS', ' '],
    ['15', 'TWS', ' ', ' ', 'DLS', ' ', ' ', ' ', 'TWS', ' ', ' ', ' ', 'DLS', ' ', ' ', 'TWS']]        

我的目标是找到距离任何字母最近的字母的距离。例如,如果我在B上调用该函数,它将返回

{"up" : 7, "down" : 7, "left" : 7, "right" : 0}

我已经尝试了内置的next函数,但我想我的问题是,是否有一种简单的方法来获取二维列表的列?

我还有一系列应被视为空的东西:

emptyList = "TWS", "DWS", "TLS", "DLS"

请帮忙。非常感谢你!

1 个答案:

答案 0 :(得分:1)

您可以使用next,并使用[row[col_num] for row in board]提取列,如下所示:

def distances(row_num, col_num):
    letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
    if not col_num.isdigit():
        col_num = ord(col_num.upper()) - ord('A') + 1
    col = [row[col_num] for row in board]
    row = board[row_num]
    return {
        'right': next((i for i, c in enumerate(row[col_num+1:]) if c in letters), 15-col_num),
        'left': next((i for i, c in enumerate(row[col_num-1:0:-1]) if c in letters), col_num-1),
        'down': next((i for i, c in enumerate(col[row_num+1:]) if c in letters), 15-row_num),
        'up': next((i for i, c in enumerate(col[row_num-1:0:-1]) if c in letters), row_num-1)
    }

print (distances(8, 'H'))

函数的参数应该是行号(8)和列号(8)或相应的字母H

要检查方块是否为空,该函数会检查内容是否不是单个字母(A-Z)。

repl.it

上查看它