简体   繁体   English

在 numpy 数组中切片和在 Python 中切片有什么区别?

[英]What is the difference between slicing in numpy arrays and slicing a list in Python?

If curr_frames is a numpy array, what does the last line mean?如果curr_frames是一个 numpy 数组,最后一行是什么意思?

curr_frames = np.array(curr_frames)

idx = map(int,np.linspace(0,len(curr_frames)-1,80))

curr_frames = curr_frames[idx,:,:,:,]

An important distinction from Python's built-in lists to numpy arrays:从 Python 的内置列表到 numpy 数组的一个重要区别:

  • when slicing in the built-in list it creates a copy .在内置列表中切片时,它会创建一个副本

     X=[1,2,3,4,5,6] Y=X[:3] #[1,2,3]

    by slicing X from 0-3 we have created a copy and stored it in the variable Y.通过将 X 从 0-3 切片,我们创建了一个副本并将其存储在变量 Y 中。

we can verify that by changing the Y and even if we change Y it does not effect X.我们可以通过改变 Y 来验证,即使我们改变 Y 也不会影响 X。

    Y[0]=20
    print(Y) # [20,2,3]
    print(X) # [1,2,3,4,5,6]
  • when slicing in numpy doesn't create a new copy but it still referring to original array在 numpy 中切片时不会创建新副本,但它仍指原始数组

    A=np.array([1,2,3,4,5,6]) B=A[:3]

By slicing A here and assigning it to B, still B referring to original array A.通过在这里切片 A 并将其分配给 B,仍然 B 指的是原始数组 A。

We can verify that by changing an element in B and it will change the value in A as well.我们可以通过改变 B 中的一个元素来验证这一点,它也会改变 A 中的值。

    B[0]=20
    print(B) # [20,2,3]
    print(A) # [20,2,3,4,5,6]

The main difference is that numpy slicing can handle multiple dimensions.主要区别在于 numpy 切片可以处理多个维度。 In your example, curr_frames[idx,:,:,:,] , the array has 4 dimensions and you are slicing by supplying the indices for one dimension ( idx ) and the : notation means to retrieve all for that dimension.在您的示例curr_frames[idx,:,:,:,] ,该数组有 4 个维度,您通过提供一维( idx )的索引进行切片, :表示法表示检索该维度的所有内容。

References:参考:

NumPy slicing NumPy 切片

Python slicing Python 切片

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

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