深入探讨Python序列神奇之处

开发 后端
Python序列的指定方法以及具体的应用方式都将会在这篇文章中向大家详细介绍,希望对此又需要的朋友们可以从中获得一些帮助。

Python编程语言这样一款功能强大的面向对象型计算机通用语言中,有很多使用方法都和那些常见的额编程语言有很大的不同之处,比如今天为大家介绍的Python序列就是其中一个。首先,我们来学习如何使用索引来取得序列中的单个项目。这也被称作是下标操作。每当你用方括号中的一个数来指定一个Python序列的时候,Python会为你抓取序列中对应位置的项目。记住,Python从0开始计数。因此,shoplist[0]抓取第一个项目,shoplist[3]抓取shoplist序列中的第四个元素。#t#

索引同样可以是负数,在那样的情况下,位置是从序列尾开始计算的。因此,shoplist[-1]表示序列的最后一个元素而shoplist[-2]抓取序列的倒数第二个项目。

切片操作符是Python序列名后跟一个方括号,方括号中有一对可选的数字,并用冒号分割。注意这与你使用的索引操作符十分相似。记住数是可选的,而冒号是必须的。

切片操作符中的第一个数(冒号之前)表示切片开始的位置,第二个数(冒号之后)表示切片到哪里结束。如果不指定第一个数,Python就从序列首开始。如果没有指定第二个数,则Python会停止在序列尾。注意,返回的序列从开始位置 开始 ,刚好在 结束 位置之前结束。即开始位置是包含在序列切片中的,而结束位置被排斥在切片外。

这样,shoplist[1:3]返回从位置1开始,包括位置2,但是停止在位置3的一个序列切片,因此返回一个含有两个项目的切片。类似地,shoplist[:]返回整个序列的拷贝。

你可以用负数做切片。负数用在从序列尾开始计算的位置。例如,shoplist[:-1]会返回除了最后一个项目外包含所有项目的序列切片。

使用Python解释器交互地尝试不同切片指定组合,即在提示符下你能够马上看到结果。Python序列的神奇之处在于你可以用相同的方法访问元组、列表和字符串。

 

 

  1. shoplist = ['apple', 'mango', 'carrot', 'banana']  
  2. # Indexing or 'Subscription' operation  
  3. print 'Item 0 is', shoplist[0]  
  4. print 'Item 1 is', shoplist[1]  
  5. print 'Item 2 is', shoplist[2]  
  6. print 'Item 3 is', shoplist[3]  
  7. print 'Item -1 is', shoplist[-1]  
  8. print 'Item -2 is', shoplist[-2]  
  9. # Slicing on a list  
  10. print 'Item 1 to 3 is', shoplist[1:3]  
  11. print 'Item 2 to end is', shoplist[2:]  
  12. print 'Item 1 to -1 is', shoplist[1:-1]  
  13. print 'Item start to end is', shoplist[:]  
  14. # Slicing on a string  
  15. name = 'swaroop' 
  16. print 'characters 1 to 3 is', name[1:3]  
  17. print 'characters 2 to end is', name[2:]  
  18. print 'characters 1 to -1 is', name[1:-1]  
  19. print 'characters start to end is', name[:]   
  20. $ python seq.py  
  21. Item 0 is apple  
  22. Item 1 is mango  
  23. Item 2 is carrot  
  24. Item 3 is banana  
  25. Item -1 is banana  
  26. Item -2 is carrot  
  27. Item 1 to 3 is ['mango', 'carrot']  
  28. Item 2 to end is ['carrot', 'banana']  
  29. Item 1 to -1 is ['mango', 'carrot']  
  30. Item start to end is ['apple', 'mango', 'carrot', 'banana']  
  31. characters 1 to 3 is wa  
  32. characters 2 to end is aroop  
  33. characters 1 to -1 is waroo  
  34. characters start to end is swaroop 

以上就是我们介绍的Python序列的全部内容。

责任编辑:曹凯 来源: 博客园
相关推荐

2009-12-23 16:13:00

WPF Attache

2009-12-14 13:33:49

Ruby与Python

2009-08-25 14:43:26

C#序列化和反序列化

2010-07-21 09:38:15

PHP缓存技术

2010-11-22 14:18:32

MySQL锁机制

2021-05-17 05:36:02

CSS 文字动画技巧

2009-11-20 17:17:08

Oracle函数索引

2011-02-25 09:23:00

Java类加载器

2015-09-02 08:57:56

JavaHashMap工作原理

2010-03-31 14:58:03

云计算

2009-08-27 11:27:58

foreach语句C# foreach语

2023-01-12 17:18:06

数据库多云

2009-10-16 09:17:39

屏蔽布线系统

2009-12-07 13:55:58

PHP array_m

2009-12-07 16:07:03

PHP类的继承

2009-12-14 14:40:10

Ruby全局域变量

2017-01-03 17:57:46

Android异步精髓Handler

2012-02-28 14:43:43

2013-07-11 09:45:48

扁平化扁平化设计

2009-11-12 13:56:54

点赞
收藏

51CTO技术栈公众号