簡體   English   中英

如何在 python 中查找二維數組中的值?

[英]How to find a value in a 2D array in python?

我正在為學校制作棋盤游戲,我希望能夠找到他們所擁有的位置編號的索引,並將棋盤上的數字替換為他們的計數器(“x”或“y”)。

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”的字符串版本並將該索引替換為其他內容?

謝謝!

您需要遍歷主列表,然后可以使用list.index()查找子列表索引,例如:

def index_2d(data, search):
    for i, e in enumerate(data):
        try:
            return i, e.index(search)
        except ValueError:
            pass
    raise ValueError("{!r} is not in list".format(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

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

我在下面添加了額外的一行。 數組采用整數值但不采用元組/列表。 因此,上面的@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 ']
]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM