简体   繁体   English

Python-Numpy数组索引作为元组

[英]Python - Numpy array index as tuple

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 ? 现在,当我以这种方式索引c矩阵时,是否使用元组索引? If yes, how is possible to have a tuple with ':' inside ? 如果是,怎么可能有一个带有':'的元组?

The colon syntax is syntactical sugar for a slice(..) object. 冒号语法是slice(..)对象的语法糖。 Your expression is equvalent to: 您的表达等效于:

#        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: 切片语法到slice(..)对象的映射如下:

  1. the colon : is equivalent to slice(None) ; 冒号:相当于slice(None)
  2. if it is :b , then it is equivalent to slice(b) ; 如果是:b ,则等效于slice(b)
  3. a: is equivalent to slice(a, None) ; a:相当于slice(a, None) ;
  4. a:b is equivalent to slice(a, b) ; a:b相当于slice(a, b) ;
  5. ::c is equivalent to slice(None, None, c) ; ::c等效于slice(None, None, c) ;
  6. :b:c to slice(None, b, c) ; :b:c slice(None, b, c) ;
  7. a::c is equivalent to slice(a, None, c) ; a::c相当于slice(a, None, c) ; and
  8. a:b:c to slice(a, b, c) . a:b:c slice(a, b, c)

Note that slice syntax is only supported in the context of an itemgetter (so x[..] ). 请注意,仅在itemgetter的上下文中支持切片语法(因此x[..] )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM