列表
定义: L=[]. 逗号分隔元素, 元素可以是任意类型
animals=['cat', 'dog', 'koala', 4, 10, 30]
#本质 animals=list(['cat', 'dog', 'koala', 4, 10, 30])
1 animals=['cat', 'dog', 'koala', 4, 10, 30] 2 print(type(animals))
>>> <class 'list'>
3 print(animals[2])
>>> koala
4 print(animals[1:3])
>>> ['dog', 'koala']
5 animals.append('bull')
6 print(animals)
>>> ['cat', 'dog', 'koala', 4, 10, 30, 'bull']
pop按照索引
1 animals.pop() #默认pop最后一个元素
>>> 'bull' 2 animals.pop()
>>> 30 3 animals.pop(0) #可以按索引pop
>>> 'cat' 4 animals.pop(0)
>>> 'dog' 5 animals.pop(1)
>>> 4
remove按照值
1 animals.remove('koala') 2 print(animals)
>>> [10]
1 animals.__len__() 2 print(len(animals))
>>> 1
1 animals=['cat', 'dog', 'cat', 'koala', 4, 10, 30] 2 print('dog' in animals)
>>> True
其他操作(掌握)
1 animals=['cat', 'dog', 'cat', 'koala', 4, 10, 30] 2 animals.insert(2, 'Ox') 3 print(animals)
>>> ['cat', 'dog', 'Ox', 'cat', 'koala', 4, 10, 30]
其他操作(了解)
1 animals=['cat', 'dog', 'cat', 'koala', 4, 10, 30] 2 animals.clear() 3 print(animals)
>>> []
1 animals=['cat', 'dog', 'cat', 'koala', 4, 10, 30] 2 L=animals.copy() 3 print(L)
>>> ['cat', 'dog', 'cat', 'koala', 4, 10, 30]
1 print(animals.count('cat'))
>>> 2
1 animals.append('bull1') 2 animals.append('bull2') 3 animals.append('bull3') 4 print(animals)
>>> ['cat', 'dog', 'cat', 'koala', 4, 10, 30, 'bull1', 'bull2', 'bull3']
5 animals.extend(['bull1', 'bull2', 'bull3']) 6 print(animals)
>>> ['cat', 'dog', 'cat', 'koala', 4, 10, 30, 'bull1', 'bull2', 'bull3', 'bull1', 'bull2', 'bull3']
1 print(animals.index('cat'))
>>> 0 2 animals.reverse() 3 print(animals)
>>> ['bull3', 'bull2', 'bull1', 'bull3', 'bull2', 'bull1', 30, 10, 4, 'koala', 'cat', 'dog', 'cat']
1 L=[3, -1, 5, 2] 2 L.sort(reverse=True) 3 print(L)
>>> [5, 3, 2, -1]
用列表模拟队列与堆栈
1 # 对列特点:先进先出、后进后出 2 # 用列表insert、pop模拟进队出队: 3 l = [] 4 l.insert(0,'i1') 5 l.insert(0,'i2') 6 l.insert(0,'i3') 7 l 8 >>> ['i3', 'i2', 'i1'] 9 l.pop() 10 >>> 'i1' 11 l.pop() 12 >>> 'i2' 13 l.pop() 14 >>> 'i3' 15 16 # 用列表append、pop模拟进队出队: 17 l = [] 18 l.append('a1') 19 l.append('a2') 20 l.append('a3') 21 l 22 >>> ['a1', 'a2', 'a3'] 23 l.pop(0) 24 >>> 'a1' 25 l.pop(0) 26 >>> 'a2' 27 l.pop(0) 28 >>> 'a3' 29 30 # 堆栈特点:先进后出、后进先出 31 # 用列表insert、pop方法模拟进栈出栈: 32 l = [] 33 l.insert(0,'i1') 34 l.insert(0,'i2') 35 l.insert(0,'i3') 36 l 37 >>> ['i3', 'i2', 'i1'] 38 l.pop(0) 39 >>> 'i3' 40 l.pop(0) 41 >>> 'i2' 42 l.pop(0) 43 >>> 'i1' 44 45 # 用列表append、pop方法模式进栈出栈: 46 l = [] 47 l.append('a1') 48 l.append('a2') 49 l.append('a3') 50 l 51 >>> ['a1', 'a2', 'a3'] 52 l.pop() 53 >>> 'a3' 54 l.pop() 55 >>> 'a2' 56 l.pop() 57 >>> 'a1'