社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

python中的board[x,y]`和board[x][y]`有区别吗?

Broski-AC • 5 年前 • 1916 次点击  

我正在通过一个 tutorial on GeekforGeeks website 注意到他们正在使用 board[x,y] ,这是我从未见过的。我不认为这行得通,但当我运行程序时,一切都按预期进行。

我试着用上面概述的方法运行一个更小的代码示例,而不是我更熟悉的方法( board[x][y] )但是当我运行代码时 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) 

有人能解释一下为什么吗 董事会 有效,到底发生了什么?我以前从来没有见过这个,除了创建列表,也没有从概念上理解它。

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/39499
 
1916 次点击  
文章 [ 6 ]  |  最新文章 5 年前
LiuXiMin
Reply   •   1 楼
LiuXiMin    5 年前

在python中, [] __getitem__ ,很容易重写。

而且, 1, 2 在python中会给我们一个元组。是的,我们不需要 () 创建非空元组。

所以,努比可以很容易地做到这一点,甚至我也可以。

In [1]: 1, 1
Out[1]: (1, 1)

In [2]: type(_)
Out[2]: tuple

In [3]: a = {(1, 1): 3}

In [4]: a[1, 1]
Out[4]: 3

In [5]: a[(1, 1)]
Out[5]: 3

In [6]: class NumpyArray(list):
   ...:     def __getitem__(self, index):
   ...:         if isinstance(index, tuple) and len(index) == 2:
   ...:             return self[index[0]][index[1]]
   ...:         return super().__getitem__(index)
   ...:

In [7]: b = NumpyArray([[0, 1], [2, 3]])

In [8]: b[1, 1]
Out[8]: 3

您可以使用下面的代码在自己的ipython上进行尝试。

class NumpyArray(list):
    def __getitem__(self, index):
        if isinstance(index, tuple) and len(index) == 2:
            return self[index[0]][index[1]]
        return super().__getitem__(index)

b = NumpyArray([[0, 1], [2, 3]])
b[1, 1]
smci
Reply   •   2 楼
smci    5 年前

因为他们 board 或者是 numpy.ndarray 或是包裹它的某种类型,例如。 pandas.DataFrame

你应该做的 type(board) . 或者显示创建和初始化的行 .

另外,当你说“当我运行程序时,一切都按预期进行”时,你应该以交互模式运行( python -i ,然后可以运行以下查询 类型(板)

jfaccioni
Reply   •   3 楼
jfaccioni    5 年前

这个 board[x, y] 语法可能应用于numpy数组,该数组接受此语法以实现行/列索引的切片操作。看看这些例子:

>>> x = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])  # creates 2D array
>>> x
array([[1, 2, 3],
       [4, 5, 6],
       [7, 8, 9]])

>>> x[1]  # get second row (remember, index starts at 0)
array([4, 5, 6])

>>> x[:, 2]  # get third column
array([3, 6, 9])

>>> x[1, 2]  # get element on second row, third column
6

>>> x[1][2]  # same as before but with non-broadcasting syntax (i.e. works for lists as you are used to)
6

>>> x[1, 0:2]  # get first two elements of second row  
array([4, 5])

>>> x[0:2, 0:2]  # subsets the original array, "extracting" values from the first two columns/rows only
array([[1, 2],
       [4, 5]])

当然,写作 my_list[x, y] 引发错误,因为 x, y 实际上是元组 (x, y) ,常规列表不能将元组用作索引值。

Grismar
Reply   •   4 楼
Grismar    5 年前

它实际上在基本python中不起作用(如您的示例)。如果运行代码,python将引发异常:“typeerror:列表索引必须是整数或切片,而不是元组”。

这个 1, 1 传递给 board 被解释为一个元组,并且由于board应该用整数或切片索引,所以这不起作用。

但是,如果 如果是某种类似数组的数据结构,并且开发人员已经实现了对元组索引的支持,那么这是可行的。这方面的一个例子是 numpy .

Ant
Reply   •   5 楼
Ant    5 年前

这是因为它们使用的对象(在本例中是numpy数组)重载了 __getitem__ 方法。请看这个玩具示例:

class MyArray:
  def __init__(self, arr):
    self.arr = arr
  def __getitem__(self, t):
    return self.arr[t[0]][t[1]]

myarr = MyArray([[1,1,1], [1,2,2], [1,2,2]])
print(myarr[0,1])
U10-Forward
Reply   •   6 楼
U10-Forward    5 年前

他们能做到这一点,因为他们使用的是numpy,这不会造成错误。

>>> 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
>>>