原标题:「Python基础知识」Python通用序列操作

列表和字符串都是Python中的序列类型,它们有很多共同特性,如都可以进行“+”操作和“*”操作,都可以使用for循环迭代等。

为什么要使用序列呢?通过图中有序与无序的对比可能会得出答案,在很多情况下,有序的序列可能会更加方便操作。

序列是有序元素的集合。在计算机中,序列的一个典型示例就是在内存中保存数据,内存的地址是从小到大有序排列的,每一个地址存放一个数据,如图所示。

实际上,Python中的序列有一些操作是通用的,即可以用到每一种序列类型中。以下序列操作分别用列表和字符串举例。

1. min()函数和max()函数

min()函数和max()函数分别返回序列的最小项和最大项。

>>> numbers = [15, -2, 3, 42, 102] >>> max(numbers) 102 >>> min(numbers) -2 >>> max('Python') 'y' >>> min('Python') 'P'

2. in和not in

使用in和not in操作符来判断某个子序列是否在该序列中:

>>> 1 in [1, 2, 3] True >>> 4 not in [1, 2, 3] True >>> 'p' in 'Python' # Python区分大小写 False >>> 'yth' in 'Python' # 不仅仅可以判断单个字符 True

3. “+”和“*”

使用“+”操作符来拼接序列,使用“*”操作符来重复相接序列:

>>> 'Py' + 'thon' 'Python' >>> 'I love you!' * 5 'I love you!I love you!I love you!I love you!I love you!'

列表的“+”操作与extend()方法类似,但是“+”操作不是就地操作,有返回值:

>>> list1 = [1, 2, 3] >>> list2 = [4, 5, 6] >>> list3 = list1 + list2 >>> list3 [1, 2, 3, 4, 5, 6] >>> list4 = list1.extend(list2) >>> list4 # list4是None >>> list1 # list2追加到了list1上 [1, 2, 3, 4, 5, 6]

包含数字的列表和包含字符串的列表进行“*”操作:

>>> numbers_list = [1] * 3 >>> strings_list = ['Python'] * 3 >>> numbers_list [1, 1, 1] >>> strings_list ['Python', 'Python', 'Python'] >>> numbers_list[0] = 3 >>> strings_list[0] = 'C' >>> numbers_list [3, 1, 1] >>> strings_list ['C', 'Python', 'Python']

4. 索引和切片

索引和切片都是通用的序列操作,因此,不仅列表有索引和切片,字符串也有索引和切片:

>>> word = 'Python' >>> word[0] # 第1个字符 'P' >>> word[-2] # 倒数第2个字符'o' >>> word[:2] # 前2个字符 'Py' >>> word[:2] + word[2:] # 字符拼接 'Python' >>> word[-3:] # 后3个字符 'hon'

5. len()函数

len()函数用于获取序列的长度:

>>> words = """Python is a programming language that lets you work quickly and integrate systems more effectively.""" >>> len(words) 99 >>> lists_ = ['Python', 312, []] >>> len(lists) 3

6. index()方法

序列中的index()方法用于查找第一个出现指定子序列的索引位置,如果不存在,那么会抛出ValueError异常:

>>> word = 'banana' >>> word.index('a') 1 >>> word.index('na') 2 >>> word.index('an') 1 >>> word.index('c') Traceback (most recent call last): File "", line 1, in ValueError: substring not found

index()方法也可以指定查找范围,即查找索引位置的起始值和结束值:

>>> numbers = [3, 1, 4, 1, 5] >>> numbers.index(1) 1 >>> numbers.index(1, 2) 3 >>> word = 'banana' >>> word.index('a', 2, 4) 3

7. count()方法

不仅仅是列表,每一种序列类型都有count()方法:

>>> word = 'banana' >>> word.count('a') 3 >>> word.count('na') 2 >>> word.count('c') 0 >>> numbers = [1, 0, 1, 0, 1, 1] >>> numbers.count(0) 2 >>> numbers.count(1) 4

相关文章