矩阵x [i,j]和x [i] [j]两种形式之间的python差异 [英] python difference between the two form of matrix x[i,j] and x[i][j]
问题描述
我想了解x[i,j]
和x[i][j]
的区别,其中x是矩阵
i want to understand the difference between x[i,j]
and x[i][j]
where x is a matrix
x = np.zeros((N,M))
我在进行研究时发现的答案始终是关于二维尺寸的数组,但是在我的情况下,我有一个带有两个索引的矩阵以与i和j一起工作,我需要使用for循环根据索引来操纵矩阵
The answer that i found while doing the research is always about array with 2D dimension but in my case i have a matrix with two index to work with i and j and i need to manipulate the matrix according the index with a for loop.
for i in range(1,N+1):
for j in range(1,M+1):
x[i-1][j-1]=random.uniform(5,10)
所以您能帮助我理解x[i,j]
和x[i][j]
之间的区别吗?为了更清楚地说明每个i(基站)有j个(用户)
so can you help me understand the difference between x[i,j]
and x[i][j]
and to be more clear for each i(base station) there is a number of j (users)
推荐答案
对于2d数组的简单索引编制,两种形式都可以工作:
For simple indexing of a 2d array both forms work:
In [28]: x = np.arange(6).reshape(2,3)
In [29]: x
Out[29]:
array([[0, 1, 2],
[3, 4, 5]])
In [30]: x[1,2]
Out[30]: 5
In [31]: x[1][2]
Out[31]: 5
对于np.matrix
(无论如何您可能都不应该使用它们)不是:
For np.matrix
(which you probably shouldn't be using anyways) they aren't:
In [32]: X = np.matrix(x)
In [33]: X
Out[33]:
matrix([[0, 1, 2],
[3, 4, 5]])
In [34]: X[1,2]
Out[34]: 5
In [35]: X[1][2]
...
IndexError: index 2 is out of bounds for axis 0 with size 1
这两种形式在语法上并不相同. [1][2]
首先使用1进行索引,然后使用2进行结果索引.这与同时使用两个参数进行索引不同.
The two forms are not syntactically the same. [1][2]
first indexes with 1, and then indexes the result with 2. That's not the same as indexing once with both parameters.
In [36]: x[1]
Out[36]: array([3, 4, 5]) # (3,) shape
In [37]: X[1]
Out[37]: matrix([[3, 4, 5]]) # (1,3) shape
出现错误是因为np.matrix
返回另一个np.matrix
.因此,下一个[2]
索引将再次索引第一个维度.
The error arises because np.matrix
returns another np.matrix
. So the next [2]
indexing will again be indexing the first dimension.
x[1]
实际上是x[1,:]
的缩写,也就是说,索引第一个维度,然后切片其余所有维度(或X[1,...]
允许3d或更高).所以x[1][2]
确实是
x[1]
is really short for x[1,:]
, that is, index the first dimension, and slice all the rest (or X[1,...]
to allow for 3d and higher). So x[1][2]
is really
temp = x[1,:]
temp[2]
或对于矩阵情况:
temp = X[1,:]
temp[2,:]
换句话说,它是2个索引操作.这是一个Python表达式,而不是特定的numpy
用法.
In other words, it is 2 indexing operations. It's a Python expression, not a specific numpy
usage.
当我们用列表或切片建立索引时,两种形式之间的差异变得尤为重要,尤其是在设置值时.
When we index with lists or slices, the difference between the two forms becomes more significant, especially when setting values.
我鼓励初学者使用x[i,j]
表格.除非您真的了解发生了什么,否则不要使用x[1][2]
.
I encourage beginners to use the x[i,j]
form. Don't use x[1][2]
unless you really understand what is going on.
如果需要,我可以研究如何将索引转换为对__setitem__
和__getitem__
的调用.
If needed I could get into how indexing is translated into calls to __setitem__
and __getitem__
.
这篇关于矩阵x [i,j]和x [i] [j]两种形式之间的python差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!