2017-07-18 80 views
0

我正在爲學校製作一個棋盤遊戲,我希望能夠找到他們所在的地點編號的索引,並用他們的計數器(「x」或「y」)替換棋盤上的數字。如何在python中找到二維數組中的值?

board = [ 
    ["43","44","45","46","47","48","49"], 
    ["42","41","40","39","38","37","36"], 
    ["29","30","31","32","33","34","35"], 
    ["28","27","26","25","24","23","22"], 
    ["15","16","17","18","19","20","21"], 
    ["14","13","12","11","10","9 ","8 "], 
    ["1 ","2 ","3 ","4 ","5 ","6 ","7 "] 

    ] 

for line in board: 
    print (line) 
roll = input("Player " + player + " press enter to roll the dice") 
print ("Your counter is",counter) 

if roll != "blablabla": 
    die1 = random.randint(1,6) 
    die2 = random.randint(1,6) 
    dice = die1 + die2 
    print (die1) 
    print (die2) 
    print ("You rolled",dice) 

if player == "one": 
    place1 =(place1+dice) 
    print ("P1's place is",place1) 
else: 
    place2 =(place2+dice) 
    print ("P2's place is",place2) 

如何在板中找到字符串版本的「place1」或「place2」,並用其他內容替換該索引?

謝謝!

+2

Python列表有一個'index(value)'方法 – Grimmy

回答

0

您需要遍歷你的主目錄,然後你可以使用list.index()找到子列表索引,例如:

def index_2d(data, search): 
    for i, e in enumerate(data): 
     try: 
      return i, e.index(search) 
     except ValueError: 
      pass 
    raise ValueError("{} is not in list".format(repr(search))) 

它將準確地採取行動作爲list.index(),但對於二維陣列,所以在你的情況下:

position = index_2d(board, "18") # (4, 3) 
print(board[position[0]][position[1]]) # 18 

position = index_2d(board, "181") # ValueError: '181' is not in list 
+1

@Downvoter - 建設性的批評是受歡迎的。 – zwer

0

ind = np.where(np.array(board) == str(place1))將返回board數組中所有元素的索引等於place。要替換這些值,請執行以下操作:board[ind] = newval

基本上,

import numpy as np 
ind = np.where(np.array(board) == str(place1)) 
board[ind] = newval 
0

我已經添加了一個在額外的線以下。數組採用整數值而不是元組/列表。所以,上面的@zwer已經給出了代碼片段中的下面一行。感謝@ zwer。

board[position[0]][position[1]] = 'Replaced' 



def index_2d(data, search): 
    for i, e in enumerate(data): 
     try: 
      return i, e.index(search) 
     except ValueError: 
      pass 
    raise ValueError("{} is not in list".format(repr(search))) 


board = [ 
    ["43","44","45","46","47","48","49"], 
    ["42","41","40","39","38","37","36"], 
    ["29","30","31","32","33","34","35"], 
    ["28","27","26","25","24","23","22"], 
    ["15","16","17","18","19","20","21"], 
    ["14","13","12","11","10","9 ","8 "], 
    ["1 ","2 ","3 ","4 ","5 ","6 ","7 "] 

    ] 

position = index_2d(board, "21") 
board[position[0]][position[1]] = 'Replaced' 
print("{}".format(board)) 

輸出結果會像是一樣,注意「替換」。

[ 
['43', '44', '45', '46', '47', '48', '49'], 
['42', '41', '40', '39', '38', '37', '36'], 
['29', '30', '31', '32', '33', '34', '35'], 
['28', '27', '26', '25', '24', '23', '22'], 
['15', '16', '17', '18', '19', '20', 'Replaced'], 
['14', '13', '12', '11', '10', '9 ', '8 '], 
['1 ', '2 ', '3 ', '4 ', '5 ', '6 ', '7 '] 
] 
相關問題