list是一种有序的集合(或称作列表),可以很方便地添加和删除其中的元素
1 >>> classmates = ['Michael', 'Bob', 'Tracy']
可通过序号访问各元素,序号范围:-n ~ n-1,当索引超出了范围时,Python会报一个IndexError错误,序号-1 相当于n-1,-2相当于n-2,-n相当于n-n=0
1 >>> classmates[-1] 2 'Tracy' 3 >>> classmates[2] 4 'Tracy'
1 >>> classmates = ['Michael', 'Bob', 'Tracy'] 2 >>> classmates[-10] 3 Traceback (most recent call last): 4 File "<pyshell#11>", line 1, in <module> 5 classmates[-10] 6 IndexError: list index out of range
append(...)新增元素:classmates.append('Miranda')
insert(... , ...)插入元素到指定位置:classmates.insert(2,'John') 第一个参数是序号,不是第几个
1 >>> classmates.append('Miranda') 2 >>> classmates 3 ['Michael', 'Bob', 'Tracy', 'Miranda'] 4 >>> classmates.insert(2,'John') 5 >>> classmates 6 ['Michael', 'Bob', 'John', 'Tracy', 'Miranda']
pop()删除末尾元素:classmates.pop()
pop(...)删除指定位置的元素:classmates.pop(1) 第一个参数是序号,不是第几个
1 >>> classmates.pop() 2 'Miranda' 3 >>> classmates.pop(1) 4 'Bob' 5 >>> classmates 6 ['Michael', 'John', 'Tracy']
remove(...)删除指定值第一次出现的位置所在元素:classmates.remove('Bob')
count(...)统计指定值出现的次数:classmates.count('Bob')
1 >>> classmates 2 ['Michael', 'Bob', 'Tracy', 'Bob'] 3 >>> classmates.remove('Bob') 4 >>> classmates 5 ['Michael', 'Tracy', 'Bob'] 6 >>> classmates.count('Bob') 7 1
1 >>> classmates 2 ['Michael', 'Tracy', 'Bob'] 3 >>> len(classmates) 4 3 5 >>> classmates+['John'] 6 ['Michael', 'Tracy', 'Bob', 'John'] 7 >>> ['hhh']*5 8 ['hhh', 'hhh', 'hhh', 'hhh', 'hhh']
不能将一个列表和一个字符串合并到一起,除非先把列表转化为字符串,或者把字符串转化为列表 list的元素的数据类型可以不同
1 >>> str([1,2])+"34" #same as "[1,2]"+"34" 2 '[1, 2]34' 3 >>> [1,2]+list("34") #same as [1,2]+['3','4'] 4 [1, 2, '3', '4']
1 >>> 3 in [1,2,3] 2 True 3 >>> for x in [1,2,3]: 4 print(x,end='#') 5 6 7 1#2#3#
>>> res=[x*3 for x in 'hello'] >>> res ['hhh', 'eee', 'lll', 'lll', 'ooo'] >>> res=[] >>> for x in 'hello': res.append(x*3) >>> res ['hhh', 'eee', 'lll', 'lll', 'ooo']
list元素也可以是另一个list
1 >>> s = ['python', 'java', ['asp', 'php'], 'scheme'] 2 3 >>> len(s) 4 4 5 6 >>> s[2][1] 7 'asp'
>>> kk=[1,2,3,4,5,6] >>> kk[-5] 2 >>> kk[-5:-2] #包含前一个序号的元素,不包含后一个 [2, 3, 4] >>> kk[1:4] #相当于kk[1:4] [2, 3, 4]
>>> kk[1:] #从序号1一直到最后 [2, 3, 4, 5, 6]
1 >>> matrix=[[1,2,3],[4,5,6],[7,8,9]] 2 >>> matrix[1] 3 [4, 5, 6] 4 >>> matrix[1][1] 5 5 6 7 >>> matrix=[[1,2,3], 8 [4,5,6], 9 [7,8,9]] 10 >>> matrix[1] 11 [4, 5, 6] 12 >>> matrix[1][1] 13 5
1 >>> kk=[1,2,3,4] 2 >>> kk[1]=7 3 >>> kk 4 [1, 7, 3, 4] 5 >>> kk[1:3]=[8,9] 6 >>> kk 7 [1, 8, 9, 4] 8 >>> kk[1:2]=[10,11,12] #长度不一定要一样 9 >>> kk 10 [1, 10, 11, 12, 9, 4]
1 >>> kk=[1,2] 2 >>> kk.extend([3,4,5]) 3 >>> kk 4 [1, 2, 3, 4, 5] 5 >>> kk.index(3) #显示括号里元素的序号 6 2 7 >>> del kk[2] 8 >>> kk 9 [1, 2, 4, 5] 10 >>> del kk[1:3] 11 >>> kk 12 [1, 5]
1 >>> kk=[1,2,3,4,5] 2 >>> kk[1:]=[] 3 >>> kk 4 [1] 5 >>> kk=[1,2,3,4,5] 6 >>> kk[1]=[] 7 >>> kk 8 [1, [], 3, 4, 5]