2

我一直在查看并解释一些示例代码,并且在理解一些切片语法时遇到了一些麻烦。在某些情况下,我正在研究一个计算程序,该程序使用有限差分法来近似正方形区域的温度。

这是一些代码:

maxIter = 500
lenX = lenY = 20 
delta = 1
Ttop = 100
Tbottom = 0
Tleft = 0
Tright = 0
Tguess = 30

T = np.empty((lenX, lenY))
T.fill(Tguess)

T[(lenY-1):, :] = Ttop
T[:1, :] = Tbottom
T[:, (lenX-1):] = Tright
T[:, :1] = Tleft

最后一点是我无法理解的。我不确定冒号和逗号在 T[] 边界条件中的确切位置。代码的下一部分继续使用 T[i,j] 进行 for 循环。就像看第一个一样,它似乎在 T 切片的第一个索引中从 9 (lenY-1) 到列表末尾,而在第二个索引中不切片任何内容,然后将其设置为 100。我知道这是在做沿顶部边界 100 的温度,我只是不确定从目前的语法来看这是如何发生的。

4

2 回答 2

2

假设x是一个具有 N 个元素的 NumPy 数组,索引为 0..N-1。可以说x[:k]表示从0..k-1开始的所有元素,x[k:]表示k..N-1,x[k1:k2]表示k1..k2-1。最后,x[:]表示所有元素。

因此,在您的代码中,四行正在设置:

  • 最后一行,所有列Ttop
  • 第一行,所有列Tbottom
  • 所有行,最后一列Tright
  • 所有行,第一列Tleft

切片文档可能是一个很好的参考:https ://docs.scipy.org/doc/numpy/reference/arrays.indexing.html

T您可以通过在 Python 命令行界面中的每次操作后打印来快速向自己证明这一点。启动 python, import numpy as np, 将lenX和更改lenY为一些小东西以使其更易于阅读,并将初始化值更改为唯一的,以便我们可以跟踪更改:

>>> lenX = lenY = 5
>>> Ttop = 100
>>> Tbottom = 200
>>> Tleft = 300
>>> Tright = 400
>>> Tguess = 30
>>> T = np.empty((lenX, lenY))
>>> T.fill(Tguess)

然后我们走了:

>>> T[(lenY-1):, :] = Ttop
>>> T
array([[ 30.,  30.,  30.,  30.,  30.],
       [ 30.,  30.,  30.,  30.,  30.],
       [ 30.,  30.,  30.,  30.,  30.],
       [ 30.,  30.,  30.,  30.,  30.],
       [100., 100., 100., 100., 100.]])
>>> T[:1, :] = Tbottom
>>> T
array([[200., 200., 200., 200., 200.],
       [ 30.,  30.,  30.,  30.,  30.],
       [ 30.,  30.,  30.,  30.,  30.],
       [ 30.,  30.,  30.,  30.,  30.],
       [100., 100., 100., 100., 100.]])
>>> T[:, (lenX-1):] = Tright
>>> T
array([[200., 200., 200., 200., 400.],
       [ 30.,  30.,  30.,  30., 400.],
       [ 30.,  30.,  30.,  30., 400.],
       [ 30.,  30.,  30.,  30., 400.],
       [100., 100., 100., 100., 400.]])
>>> T[:, :1] = Tleft
>>> T
array([[300., 200., 200., 200., 400.],
       [300.,  30.,  30.,  30., 400.],
       [300.,  30.,  30.,  30., 400.],
       [300.,  30.,  30.,  30., 400.],
       [300., 100., 100., 100., 400.]])
于 2019-12-07T05:57:37.777 回答
2

The colon expressions are transferred as slice objects to the numpy array. A comma creates a tuple. For demonstration:

class A:
    def __setitem__(self, target, data):
        print(repr(target))
        print(repr(data))

a = A()
a[17:, :] = 6

prints:

(slice(17, None, None), slice(None, None, None))
6

So you could also write:

a[(slice(17, None, None), slice(None, None, None))] = 6

in the last line to have the same result.

It is then the duty of the class (e.g. numpy array) to interpret that in a meaningful way.

于 2019-12-07T05:43:48.083 回答