我正在为学校制作棋盘游戏,我希望能够找到他们所拥有的地点编号的索引,并用他们的计数器替换棋盘上的数字(" 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"在董事会中用其他东西替换该指数?
谢谢!
答案 0 :(得分:1)
您需要遍历主列表,然后可以使用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()
完全相同,但对于2D数组,所以在你的情况下:
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 :(得分: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
答案 2 :(得分:0)
我添加了额外的下线。 Array采用整数值,但不是元组/列表。那么,代码片段中的下面一行已经由@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 ']
]