第2章 列表和元組
技術標籤:Python基礎教程(第3版)
2.1 序列概述
Python支援一種資料結構的基本概念——容器
>>>edward = ['Edward Gumby', 42]
>>>john = ['John Smith', 50]
>>>database = [edward, john]
>>>database
[['Edward Gumby', 42], ['John Smith', 50]]
2.2 通用的序列操作
1. 索引
序列中所有元素的編號從0開始遞增;使用負數索引時,從右開始往左數,-1是最後一個元素的位置;
例:
>>>greeting = 'Hello'
>>>greeting[0]
'H'
>>>greeting[-1]
'o'
>>>'Hello'[1]
'e'
>>>fourth = input('Year: ')[3]
Year: 2005
>>>fourth
'5'
2. 切片
基礎:如果第一個引數>=第2個引數的後邊,則為空序列[ ](numbers[1:1]即numbers的[1, 1)號元素不存在)
>>>tag = '<a href="http://www.python.org">Python web site</a>' >>>tag[9:30] 'http://www.python.org' >>>tag[32:-4] 'Python web site' >>>numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] #即numbers中[3,6)的元素 >>>numbers[3:6] [4, 5, 6] >>>numbers[0:1] [1] >>>numbers[-3:0] [] >>>numbers[-3:] [8, 9, 10] >>>numbers[:3] [1, 2, 3] >>>numbers[:] [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] >>>numbers [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
帶步長
>>>numbers[0:10:1]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>>numbers[0:10:2]
[1, 3, 5, 7, 9]
>>>numbers[3:6:3]
[4]
>>>numbers[::4]
[1, 5, 9]
帶 負步長(第一個引數<=第二個引數為空序列[ ])
>>>numbers[8:3:-1] [9, 8, 7, 6, 5] >>>numbers[10:0:-2] [10, 8, 6, 4, 2] >>>numbers[0:10:-2] [] >>>numbers[::-2] [10, 8, 6, 4, 2] >>>numbers[5::-2] [6, 4, 2] >>>numbers[:5:-2] [10, 8]
3. 序列相加
>>>[1, 2, 3] + [4, 5, 6]
[1, 2, 3, 4, 5, 6]
>>>'Hello, ' + 'world!'
'Hello, world!'
>>>[1, 2, 3] + 'world!'
Traceback (most recent call last):
File "<input>", line 1, in <module>
TypeError: can only concatenate list (not "str") to list
注意序列跨行相加時注意使用符號“\”,例如
a = [1, 2] \
+ [3, 4]
4. 乘法
>>>'python' * 5
'pythonpythonpythonpythonpython'
>>>[42]*10
[42, 42, 42, 42, 42, 42, 42, 42, 42, 42]
>>>[None]*10
[None, None, None, None, None, None, None, None, None, None]
5. 成員資格(in運算子)
>>>permissions = 'rw'
>>>'w' in permissions
True
>>>'x' in permissions
False
>>>users = ['mlh', 'foo', 'bar']
>>>input('Enter your user name: ') in users
Enter your user name: >? mlh
True
>>>subject = '$$$ Get rich now!!! $$$'
>>>'$$$' in subject
True
6. 長度、最大值和最小值
>>>numbers = [100, 34, 678]
>>>len(numbers)
3
>>>max(numbers)
678
>>>min(numbers)
34
>>>max(2, 3)
3
>>>min(9, 3, 2, 5)
2
2.3 列表:Python的主力(元組可用作對映中的鍵以及集合的成員,而列表不行)
1. 函式list
>>>list('Hello')
['H', 'e', 'l', 'l', 'o']
2. 函式的基本操作
修改
>>>x = [1, 1, 1]
>>>x[1] = 2
>>>x
[1, 2, 1]
刪除
>>>names = ['Alice', 'Beth', 'Cecil', 'Dee-Dee', 'Earl']
>>>del names[2]
>>>names
['Alice', 'Beth', 'Dee-Dee', 'Earl']
>>>del names[1:3]
>>>names
['Alice', 'Earl']
給切片賦值
>>>name = list('Perl')
>>>name
['P', 'e', 'r', 'l']
#'ar'長度<=names[2:]的長度,name的長度不變
>>>name[2:] = list('ar')
>>>name
['P', 'e', 'a', 'r']
>>>name = list('Perl')
#'ython'長度>names[1:]的長度,name的長度變大
>>>name[1:] = list('ython')
>>>name
['P', 'y', 't', 'h', 'o', 'n']
>>>numbers = [1, 5]
#numbers[1:1]為空列表,該命令為在下標為1的位置插入列表[2, 3, 4]
>>>numbers[1:1] = [2, 3, 4]
>>>numbers
[1, 2, 3, 4, 5]
#該命令為刪除元素numbers[1:4],即numbers列表中[1,4)位置的元素
>>>numbers[1:4]=[]
>>>numbers
[1, 5]
3. 列表方法
append、extend
>>>lst = [1, 2, 3]
>>>lst.append(4)
>>>lst
[1, 2, 3, 4]
#效率高於a = a + b
#等效於a[len(a):] = b(可讀性低)
>>>a = [1, 2, 3]
>>>b = [4, 5, 6]
>>>a.extend(b)
>>>a
[1, 2, 3, 4, 5, 6]
clear 相當於lst[:] = []或者lst = []
>>>lst = [1, 2, 3]
>>>lst.clear()
>>>lst
[]
複製copy
>>>a = [1, 2, 3]
>>>b = a
>>>b[1] = 4
>>>a
[1, 4, 3]
>>>a = [1, 2, 3]
>>>b = a.copy()
>>>b[1] = 4
>>>a
[1, 2, 3]
count
>>>['to', 'be', 'or', 'not', 'to', 'be'].count('to')
2
>>>x = [[1, 2], 1, 1, [2, 1, [1, 2]]]
>>>x.count(1)
2
>>>x.count([1, 2])
1
index
>>>knights = ['We', 'are', 'the', 'knights', 'who', 'say', 'ni']
>>>knights.index('who')
4
>>>knights.index('herring')
Traceback (most recent call last):
File "<input>", line 1, in <module>
ValueError: 'herring' is not in list
insert
>>>numbers = [1, 2, 3, 5, 6, 7]
#等效於numbers[3:3] = ['four'](可讀性低)
>>>numbers.insert(3, 'four')
>>>numbers
[1, 2, 3, 'four', 5, 6, 7]
pop(以及棧和佇列的實現)
pop是唯一既修改列表又返回一個非None值的列表方法;
pop()彈出列表最後的元素;
pop(0)彈出列表最前的元素;
Python中沒有提供push函式,可以使用append替代;
#基本操作
>>>x = [1, 2, 3]
>>>x.pop()
3
>>>x
[1, 2]
>>>x.pop(0)
1
>>>x
[2]
棧的實現:
1)出棧pop(),入棧append(),即列表尾為棧頂
2)出棧pop(0),入棧insert(0, key),即列表首為棧頂
佇列的實現:
1)出隊pop(0),入隊append(),即列表頭為隊頭,列表尾為隊尾
2)出隊pop(),入隊insert(0, key),即列表頭為隊尾,列表尾為隊頭
3)使用模組collections中的deque,在後續學習中詳細說明
remove remove引數為列表中的第一個指定值的元素,例如x.remove('be');del引數為列表下標,例如del x[1];
>>>x = ['to', 'be', 'or', 'not', 'to', 'be']
>>>x.remove('be')
>>>x
['to', 'or', 'not', 'to', 'be']
>>>x.remove('bee')
Traceback (most recent call last):
File "<input>", line 1, in <module>
ValueError: list.remove(x): x not in list
reverse
>>>x = [1, 2, 3]
>>>x.reverse()
>>>x
[3, 2, 1]
#reversed函式返回一個迭代器,按相反的順序迭代序列;list將返回的物件轉換為列表;
>>>x = [1, 2, 3]
>>>list(reversed(x))
[3, 2, 1]
排序
sort函式對列表就地排序,不返回引數;
sorted函式不對列表進行修改,返回排序後的列表;
>>>x = [4, 6, 2, 1, 7, 9]
>>>x.sort()
>>>x
[1, 2, 4, 6, 7, 9]
>>>x = [4, 6, 2, 1, 7, 9]
>>>y = sorted(x)
>>>x
[4, 6, 2, 1, 7, 9]
>>>y
[1, 2, 4, 6, 7, 9]
>>>sorted('Python')
['P', 'h', 'n', 'o', 't', 'y']
sort函式有兩個引數:
1)key引數,類似於C++中的自定義排序函式cmp;
2)reverse引數,值為True/False,表示是否按照相反的順序對列表進行排序
>>>x = ['aardvark', 'abalone', 'acme', 'add', 'aerate']
>>>x.sort(key=len)
>>>x
['add', 'acme', 'aerate', 'abalone', 'aardvark']
>>>x = [4, 6, 2, 1, 7, 9]
>>>x.sort(reverse=True)
>>>x
[9, 7, 6, 4, 2, 1]
2.4 元組:不可修改的序列(元組可用作對映中的鍵以及集合的成員,而列表不行)
>>>1, 2, 3
(1, 2, 3)
>>>(1, 2, 3)
(1, 2, 3)
>>>()#空元組
()
>>>x = 1, 2, 3
>>>x[1]
2
>>>x[0:2]
(1, 2)
建立只包含一個值的元組,一定注意使用逗號
>>>42,
(42,)
>>>(42,)
(42,)
#而>>>42只表示實數42
>>>3 * (40 + 2)
126
>>>3 * (40 + 2,)
(42, 42, 42)
tuple將列表、字串、元組轉換為元組
>>>tuple([1, 2, 3])
(1, 2, 3)
>>>tuple('abc')
('a', 'b', 'c')
>>>tuple((1, 2, 3))
(1, 2, 3)