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