Python 的切片操作以及 利用步长对序列进行倒序取值

来源:互联网 发布:网络机顶盒ir接口 编辑:程序博客网 时间:2024/06/04 23:36

切片操作:

对于具有序列结构的数据来说,切片操作的方法是:consequence[start_index: end_index: step]。

start_index:表示是第一个元素对象,正索引位置默认为0;负索引位置默认为 -len(consequence)

end_index:表示是最后一个元素对象,正索引位置默认为 len(consequence)-1;负索引位置默认为 -1。

step:表示取值的步长,默认为1,步长值不能为0。

几种常见的表达:

con[start_index: ]:缺省end_index,表示从start_index开始到序列中最后一个对象。

con[: end_index]:缺省start_index,表示从序列中第一个对象到end_index-1之间的片段。

con[:]:缺省start_index和end_index,表示从第一个对象到最后一个对象的完整片段。

con[::step]:缺省start_index和end_index,表示对整个序列按照索引可以被step整除的规则取值。



在使用单索引对序列寻址取值时,你所输入的索引值必须是处于 -len(consequence) 到 len(consequence)-1 之间的值,否则会报错提示索引值超出范围。如:

  1. >>> a=[1,2,3,4,5,6,7] 
  2. >>> a[len(a)-1] 
  3. >>> a[-len(a)] 
  4. >>> a[len(a)] 
  5.   
  6. Traceback (most recent call last): 
  7.   File "<pyshell#98>", line 1, in <module> 
  8.     a[len(a)] 
  9. IndexError: list index out of range 
  10. >>> a[-len(a)-1] 
  11.   
  12. Traceback (most recent call last): 
  13.   File "<pyshell#99>", line 1, in <module> 
  14.     a[-len(a)-1] 
  15. IndexError: list index out of range 


利用步长对序列进行倒序取值:


  1. >>> a=[1,2,3,4,5,6,7] 
  2. >>> b=(1,2,3,4,5,6,7) 
  3. >>> c='Let me show you a little thing' 
  4. >>> a[::-1] 
  5. [7, 6, 5, 4, 3, 2, 1] 
  6. >>> b[::-1] 
  7. (7, 6, 5, 4, 3, 2, 1) 
  8. >>> c[::-1] 
  9. 'gniht elttil a uoy wohs em teL' 
  10. >>> a 
  11. [1, 2, 3, 4, 5, 6, 7] 
  12. >>> b 
  13. (1, 2, 3, 4, 5, 6, 7) 
  14. >>> c 
  15. 'Let me show you a little thing' 
  16.   
  17. >>> a.reverse() 
  18. >>> a 
  19. [7, 6, 5, 4, 3, 2, 1] 

相对reverse而言,切片的方法不会改变列表的结构,所以这是在实际应用中比较有用的一个技巧。


0 0
原创粉丝点击