在2D列表中增加一个正方形,同时减少所有未涉及的其他正方形-Python



我有一个2D列表,我试图更新一个单元格的值,而我必须递减我不递增的其他单元格的值。

我有一个叫的2D列表

PAWN = [
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0]
]

在我的代码中,我正在更新所有涉及典当移动的正方形,例如g3,h4,矩阵将像这样更新,为移动添加0,1,这很好。

PAWN = [
A  B  C  D  E  F  G  H
8  [0, 0, 0, 0, 0, 0, 0, 0],
7  [0, 0, 0, 0, 0, 0, 0, 0],
6  [0, 0, 0, 0, 0, 0, 0, 0],
5  [0, 0, 0, 0, 0, 0, 0, 0],
4  [0, 0, 0, 0, 0, 0, 0, 0.1],
3  [0, 0, 0, 0, 0, 0, 0.1, 0],
2  [0, 0, 0, 0, 0, 0, 0, 0],
1  [0, 0, 0, 0, 0, 0, 0, 0]
]

以下是我的代码片段:

white_moves = ['g3', 'h4']
for moves in white_moves:
delta = 0.1
if len(moves) == 2: # for example g3
y = moves[0]   #y = g
x = int(moves[1]) #x = 3
coordinate = {0: 'a', 1: 'b', 2: 'c', 3: 'd', 4: 'e', 5: 'f', 6: 'g', 7: 'h'}
c = coordinate.values()
for key, value in coordinate.items():
if y == value:
indice_colonna = key

for letter in c:  
if letter == y:  # if value in dictionary is equal to my y

file = open('../data/tables/pedone.csv', 'r') #reading from csv file
reader = csv.reader(file)
PAWN = list(reader)
file.close()
new_pawn = PAWN    

new_pawn[8-x][indice_colonna] = round(float(PAWN[8-x][indice_colonna]) + delta, 1) #here im incrementing the value of square [g][3]


new_pawn = open("../data/tables/pedone.csv", 'w', newline='') #updating that file
writer = csv.writer(new_pawn)
writer.writerows(PAWN)
new_pawn.close()
break

如何递减所有其他平方?从第0行到第8行,从第0列到第8列,但也避免减少g3平方?我在分离这两个操作时遇到问题

这是我尝试过的:

rows = 8
columns = 8
for i in range(rows):
for j in range(columns):
pedone[i][j] = -0.1
pedone[8-x][indice_colonna] = + 2*0.1 #trying to add 2x the value 

但不起作用,有什么建议吗?

在试图添加2倍值的循环中,每次迭代时都会覆盖整个矩阵,并且只将单个值设置为.2。您将希望将这些拆分,然后应用该操作。此外,如果您正在递增该值,则每次通过循环时该值都会增加。

这将要求您在开始时将CSV读取到矩阵中,并在结束时将其写入,而不是重复写入,除非您希望在每一次可能的移动中减去一个值,而不仅仅是一次。

rows = 8
columns = 8
# read CSV into pedone
for i in range(rows):
for j in range(columns):
pedone[i][j] -= 0.1
# and then enter your loop:
for moves in white_moves
...
pedone[8-x][indice_colonna] += 2 * 0.1
# write pedone back to CSV

这里的问题是,您既要从每个单元格中删除-0.1(这是可以的(,又要在每次迭代中将+ 2*0.1添加到目标单元格。但是,您只想添加+ 2*0.1一次!

试试这个:

rows = 8
columns = 8
pedone[8-x][indice_colonna] += 2*0.1 #trying to add 2x the value  ONE TIME ONLY
for i in range(rows):
for j in range(columns):
pedone[i][j] = -0.1

最新更新