Python多維數組切片


1. array如果維度多了,就變成ndarray。

2. list切片類似C數組,多維度分別用”[]“索引,單維度切片用”:“,如:

>>> a
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> a[1][1:3]
[5, 6]

但是這樣做第二個維度索引不起作用:

>>> a[1:3][0:2]
[[4, 5, 6], [7, 8, 9]]

把list當作ndarray去slice也是不對的:

>>> a[1:3,0:2]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: list indices must be integers or slices, not tuple

3. ndarray切片用一個”[]“里面加逗號的方式,如:

>>> a=np.round(np.random.rand(3,3)*10)
array([[9., 5., 1.], [3., 1., 5.], [2., 5., 5.]]) >>> a[1:3,0:2] array([[3., 1.], [2., 5.]])

這樣做第二個維度索引不起作用:

>>> a[1:3][0:2]
array([[3., 1., 5.],
       [2., 5., 5.]])

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM