Numpy 数组的切片操作

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

 

 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()

 

A=np.array([1,2,3,4,5,6,7,8,9,0])1234567890
下标系一Index(Left to Right)0123456789
下标系二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:1,2,3,4,5,6,7   注:Index -3处对应的数组值8。1表示从左往右,步的大小是1。所以输出1,2,3,4,5,6,7

实例: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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值