如何在python中的2D数组中查找值?
我正在为学校制作一个棋盘游戏,我希望能够找到他们拥有的牌号索引,并用他们的计数器(“x”或“y”)替换棋盘上的数字 我如何在黑板上找到“place1”或“place2”的字符串版本,并用其他索引替换该索引 谢谢大家!如何在python中的2D数组中查找值?,python,multidimensional-array,Python,Multidimensional Array,我正在为学校制作一个棋盘游戏,我希望能够找到他们拥有的牌号索引,并用他们的计数器(“x”或“y”)替换棋盘上的数字 我如何在黑板上找到“place1”或“place2”的字符串版本,并用其他索引替换该索引 谢谢大家! ind=np。其中(np.array(board)==str(place1))将返回board数组中等于place的所有元素的索引。要替换这些值,请执行以下操作:board[ind]=newval 基本上 import numpy as np ind = np.where(np.a
ind=np。其中(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
您需要迭代主列表,然后可以使用
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))
对于2D数组,它的作用与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
我在下面加了一行。数组接受整数值,但不接受元组/列表。下面是上面@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))
输出将是这样的,请注意其中的“替换”
Python列表有一个
索引(值)
方法
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 ']
]