Python - Numpy数组索引作为元组

时间:2021-12-12 12:32:46

If we create an array with Numpy , we can use many functionalities given by numpy library.

如果我们用Numpy创建一个数组,我们可以使用numpy库给出的许多功能。

For example if c is a matrix

例如,如果c是矩阵

print(c[:,1])

will print every value in the column 1.

将打印第1列中的每个值。

Now, when i index the c matrix in this way, am i indexing using a tuple ? If yes, how is possible to have a tuple with ':' inside ?

现在,当我以这种方式索引c矩阵时,我是否使用元组索引?如果是的话,怎么可能在里面有一个带有':'的元组?

1 个解决方案

#1


1  

The colon syntax is syntactical sugar for a slice(..) object. Your expression is equvalent to:

冒号语法是slice(..)对象的语法糖。你的表达方式与以下方面相同:

#        v slice object
print(c[(slice(None), 1)])
#       ^   tuple      ^

So you have passed a tuple containing a slice(None) object as first element, and 1 as second element.

因此,您传递了一个包含slice(None)对象作为第一个元素的元组,并将1作为第二个元素。

The mapping of slice syntax to slice(..) objects is as follows:

切片语法到切片(..)对象的映射如下:

  1. the colon : is equivalent to slice(None);
  2. 冒号:相当于切片(无);

  3. if it is :b, then it is equivalent to slice(b);
  4. 如果是:b,那么它相当于切片(b);

  5. a: is equivalent to slice(a, None);
  6. a:相当于slice(a,None);

  7. a:b is equivalent to slice(a, b);
  8. a:b相当于切片(a,b);

  9. ::c is equivalent to slice(None, None, c);
  10. :: c相当于slice(None,None,c);

  11. :b:c to slice(None, b, c);
  12. :b:c切片(无,b,c);

  13. a::c is equivalent to slice(a, None, c); and
  14. a :: c相当于slice(a,None,c);和

  15. a:b:c to slice(a, b, c).
  16. a:b:c切片(a,b,c)。

Note that slice syntax is only supported in the context of an itemgetter (so x[..]).

请注意,切片语法仅在itemgetter的上下文中受支持(因此x [..])。

#1


1  

The colon syntax is syntactical sugar for a slice(..) object. Your expression is equvalent to:

冒号语法是slice(..)对象的语法糖。你的表达方式与以下方面相同:

#        v slice object
print(c[(slice(None), 1)])
#       ^   tuple      ^

So you have passed a tuple containing a slice(None) object as first element, and 1 as second element.

因此,您传递了一个包含slice(None)对象作为第一个元素的元组,并将1作为第二个元素。

The mapping of slice syntax to slice(..) objects is as follows:

切片语法到切片(..)对象的映射如下:

  1. the colon : is equivalent to slice(None);
  2. 冒号:相当于切片(无);

  3. if it is :b, then it is equivalent to slice(b);
  4. 如果是:b,那么它相当于切片(b);

  5. a: is equivalent to slice(a, None);
  6. a:相当于slice(a,None);

  7. a:b is equivalent to slice(a, b);
  8. a:b相当于切片(a,b);

  9. ::c is equivalent to slice(None, None, c);
  10. :: c相当于slice(None,None,c);

  11. :b:c to slice(None, b, c);
  12. :b:c切片(无,b,c);

  13. a::c is equivalent to slice(a, None, c); and
  14. a :: c相当于slice(a,None,c);和

  15. a:b:c to slice(a, b, c).
  16. a:b:c切片(a,b,c)。

Note that slice syntax is only supported in the context of an itemgetter (so x[..]).

请注意,切片语法仅在itemgetter的上下文中受支持(因此x [..])。