Python 切片


Python 切片

什么是切片

切片是由 : 隔开的两个索引来访问一定范围内的元素。其中, 列表list、元组tuple、字符串string 都可以使用切片.

  • 代码1-1
colors = ['red', 'green', 'gray', 'black'] print(colors[1 : 3]) # ['green', 'gray'] 

为什么要使用切片

如果不使用切片,可以通过循环的方式来访问列表某个范围的元素,例如:

  • 代码1-2
colors = ['red', 'green', 'gray', 'black'] for i in range(len(colors)): if i >=1 and i < 3: print(colors[i]) # ['green', 'gray'] 

与前面的代码对比不难发现,使用切片访问一个范围内的元素更加方便

切片的使用方法

  1. 切片是从序列的左边索引开始到右边索引结束这个区间内取元素(前闭后开);如果比右边的索引值大于左边的索引则取出的是空序列
  • 代码1-3
colors = ['red', 'green', 'gray', 'black'] print(colors[1 : 3]) # ['green', 'gray'] print(colors[3 : 1]) # [] print(colors[1 : 5]) # ['green', 'gray', 'black'] 
  1. 切片的索引值可以取负数,则切片方向从序列的尾部开始
  • 代码1-4
colors = ['red', 'green', 'gray', 'black'] print(colors[-3 : -1]) # ['green', 'gray'] print(colors[-1 : -3]) # [] print(colors[-5 : -1]) # ['red', 'green', 'gray'] 
  1. 索引值可以省略,左侧默认取最小(正切为0,反切为序列长度的负值)右侧默认取最大(正切为序列长度,反切为0)
  • 代码1-5
colors = ['red', 'green', 'gray', 'black'] print(colors[ : 1]) # ['red'] print(colors[1 : ]) # ['green', 'gray', 'black'] print(colors[-1 : ]) # ['black'] print(colors[ : -1]) # ['red', 'green', 'gray'] print(colors[ : ]) # ['red', 'green', 'gray', 'black'] print(colors[1 : 1]) # [] 
  1. 切片步长,可以隔几个元素进行切片,默认的步长为 1; 步长可以为负值,则切片为逆序
  • 代码1-6
numbers = list(range(1,11)) print(numbers[1:10:2]) # [2, 4, 6, 8, 10] print(numbers[10:2:-2]) # [10, 8, 6, 4]


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM