Python中的`board [x,y]`和`board [x] [y]`之间有区别吗? [英] Is there a difference between `board[x, y]` and `board[x][y]` in Python?
问题描述
我正在通过 GeekforGeeks网站上的教程,并注意到他们正在使用board[x,y]
检查数组中的点,这是我从未见过的.我认为这行不通,但是当我运行程序时,一切都会按预期进行.
I'm working through a tutorial on GeekforGeeks website and noticed that they are checking a point in an array using board[x,y]
, which I've never seen before. I don't think this would work, but when I run the program, everything goes as expected.
我尝试使用上面概述的方法和我更熟悉的方法(board[x][y]
)运行较小的代码示例,但是当我运行代码时,得到TypeError: list indices must be integers or slices, not tuple
I tried running a smaller code example using their method outlined above vs the method I'm more familiar with (board[x][y]
), but when I run my code, I get TypeError: list indices must be integers or slices, not tuple
我的代码:
board = [[1,1,1], [1,2,2], [1,2,2]]
win = 'True'
if board[1][1] == 2:
win = 'True by normal standards'
print(win)
if board[1, 1] == 2:
win = 'True by weird standards'
print(win)
print(win)
他们的代码:
def row_win(board, player):
for x in range(len(board)):
win = True
for y in range(len(board)):
if board[x, y] != player:
win = False
continue
if win == True:
return(win)
return(win)
有人可以向我解释为什么board[x,y]
起作用,究竟发生了什么?除了创建列表之外,我从未见过这种情况,而且从概念上讲也没有掌握.
Can someone explain to me why board[x,y]
works, and what exactly is happening? I've never seen this before except to create lists, and am not grasping it conceptually.
推荐答案
由于他们使用的是NumPy,因此能够做到这一点,而不会对此造成任何错误.
They're able to do that since they're using NumPy, which won't throw an error on that.
>>> a = np.array([[1,1,1], [1,2,2], [1,2,2]])
>>> a[1,1]
2
>>> # equivalent to
>>> a = [[1,1,1], [1,2,2], [1,2,2]]
>>> a[1][1]
2
>>>
这篇关于Python中的`board [x,y]`和`board [x] [y]`之间有区别吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!