Skip to main content
 首页 » 编程设计

python之在变量中存储数组位置

2025年05月04日12lyj

我正在使用 Python 构建一个简单的游戏,将二维数组作为棋盘。我的用户可以输入数字来玩,但这些数字与棋盘上的位置关联性不是很好。

我可以将数组的位置存储在变量中,这样我就不必在每次检查条件时都写出 board[x][y] 了吗?

所以代替:

if num == 1: 
    if board[3][5] == "Z": 
        print "Not empty!" 
    else  
        board[3][5] = "Z" 

我可以使用:

if num == 1: 
    if locationOf1 == "Z": 
        print "Not Empty!" 
    else 
        locationOf1 == "Z" 

我想让 locationOf1 做的就是让我知道 board[3][5] 在哪里。如何才能做到这一点?

[已编辑] 甚至更好(这可能吗?):

locations = *[location of board[5][1],location of board[5][3]]* 
 
if locations[num] == "Z": 
        print "Not empty!" 
    else 
        locations[num]  == "Z" 

请您参考如下方法:

基于键存储信息的最简单方法是字典。您可以将值保存为元组:

locations = {1: (3, 5), 2: (4,3)} 
 
def get_location(num): 
    x, y = locations.get(num, (-1, -1, )) 
    if coords != (-1,-1):  
       return board[x,y] 
    else: 
       return None