循环切换操作数 Python 3

Switch operands in loops Python 3

我希望每次循环都能切换操作数。所以第一次通过我想添加专栏。第二次通过循环我想从列中减去。第三次我想从列中减去并从行中减去。第四次我想从列中减去并添加到行中。是否可以编写一个循环来完成此任务而不是多个循环?谢谢您的帮助!

#add            
for x in range(1,8): 
    if game[column+x][row] == 'W':
        game[column+x][row] = 'B'
    elif game[column+x][row] == 'B':
        return      
#subtract       
for x in range(1,8): 
    if game[column-x][row] == 'W':
        game[column-x][row] = 'B'
    elif game[column-x][row] == 'B':
        return
#etc....
for x in range(1,8): 
    if game[column-x][row-x] == 'W':
        game[column-x][row-x] = 'B'
    elif game[column-x][row-x] == 'B':
        return

for x in range(1,8): 
    if game[column-x][row+x] == 'W':
        game[column-x][row+x] = 'B'
    elif game[column-x][row+x] == 'B':
        return

根据你的代码,我假设你想用 'B' 标记每个 'W' 周围的单元格。这应该足够了:

neighbours = [
  (-1, -1),
  (-1,  0),
  (-1,  1),
  ( 0, -1),
  ( 0,  0),
  ( 0,  1),
  ( 1, -1),
  ( 1,  0),
  ( 1,  1)
  ]

game = [
  ['W', 'W', 'E'],
  ['' ,  '',  ''],
  ['' ,  '',  '']
]

print game

row, col = 1, 1 # center of the game's table

for x, y in neighbours:
   if game[row + x][col + y] == 'W':
      game[row + x][col + y] = 'B'

print game

我创建了一个操作数列表并遍历了 list.That 工作