码迷,mamicode.com
首页 > 编程语言 > 详细

Numpy 数组的切片操作

时间:2015-11-02 14:03:30      阅读:238      评论:0      收藏:0      [点我收藏+]

标签:

实例+解释如下(表格):关键是要明白python中数组的下标体系。一套从左往右,一套从右往左。

A=np.array([1,2,3,4,5,6,7,8,9,0]) 1 2 3 4 5 6 7 8 9 0
下标系一Index(Left to Right) 0 1 2 3 4 5 6 7 8 9
下标系二Index(Right to Left) -10 -9 -8 -7 -6 -5 -4 -3 -2 -1
A[a:b:c] a和b   确定:切片操作的范围(from a to b, exclude b.), C 确定具体切片的pace和方向(例如:1表示Left to Right,pace=1. -1表示Right to   Left,pace=1.)。
实例:A[:3:1] output: 1,2,3.   注:Index 3处对应的数组值4。1表示从左往右,步的大小是1。所以输出1,2,3
实例:A[:-3:-1] output:0,9   注:Index -3处对应的数组值8。-1表示从右往左,步的大小是1。所以输出0,9
实例:A[:3:-1] output:0,9,8,7,6,5   注:Index 3处对应的数组值4。-1表示从右往左,步的大小是1。所以输出0,9,8,7,6,5
实例:A[:-3:1]

output:0,9   注:Index -3处对应的数组值8。1表示从左往右,步的大小是1。所以输出1,2,3,4,5,6,7,8

实例:A[-3::-1]

output:8,7,6,5,4,3,2,1   注:Index -3处对应的数组值8。-1表示从右往左,步的大小是1。所以输出8,7,6,5,4,3,2,1

 

 

 

 1 import numpy as np
 2 import sys
 3 
 4 def main():
 5     A=np.array([1,2,3,4,5,6,7,8,9,0])
 6     B=A.copy()
 7     print A
 8     print same as print A,,A[:]
 9     print same as print A,,A[::1]
10     print reverse A,,A[::-1]
11     print print all elements with 2 interval,,A[::2]
12     print print elements from the 4th element with 2 interval,,A[3::2]
13     print print elements from the last 4th element with 2 interval,,A[-3::2]
14     print print elements from the 2nd to 5th element with 2 interval,,A[1:4:2]
15     print reverse print all elements with 2 interval,,A[::-2]
16     print reverse print elements from the 4th element with 2 interval,,A[3::-2]
17     print reverse print elements from the last 4th element with 2 interval,,A[-3::-2]
18     #print A[a:b:c]: a and b determine range of slide. c determine the interval and direction (forth or reverse)
19     print A[:-3:-1]
20     print A[:3:1]
21     print A[:3:-1]
22     C=A[::-1]
23     C[0]=10
24     print A is also changed as how does c change,,A
25     B[9]=0
26     print A will not be affected when B change,,A
27     print array slide from second element to the last one,,A[1:]
28     print array slide from last second element to the first one,,A[:-1]
29 
30 
31 
32 if __name__ == "__main__":
33     main()

 

Numpy 数组的切片操作

标签:

原文地址:http://www.cnblogs.com/1zhk/p/4929874.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!