「Python基礎知識」Python通用序列操作
原標題:「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