Python(二) 序列
常用的序列结构:列表、元组、字符串、字典、range、zip、enumerate 等
1. 列表
列表对象常用方法
1. append(x):将元素 x 添加到列表尾部
2. extend(可迭代对象):将可迭代对象中所有的元素添加到列表尾部
3. insert(index, x):在列表指定位置 index 处添加元素 x
4. remove(x):在列表中删除首次出现的指定元素
5. pop([index]):删除并返回列表中指定位置的元素,默认为最后一个元素
6. clear():删除列表中所有元素,会保留列表对象
7. index(x):返回第一个值为 x 的元素的下标,不存在则抛出异常
8. count(x):返回指定元素 x 在列表中的出现次数
9. reverse():对列表元素进行原地翻转
10. sort():对列表元素进行排序
11. copy():返回列表对象的浅复制
1.1 列表创建、元素的增加、元素的删除
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
| a_list = [1, "Hello", "World"] print(a_list) print(type(a_list)) print(list("Hello World!")) print()
a_list += [7] print("元素增加方法1:") print(a_list) print()
a_list.append("two") print("元素增加方法2:") print(a_list) print()
a_list.extend(["three1", "three2"]) print("元素增加方法3:") print(a_list) print()
a_list.insert(0, 99) print("元素增加方法4:") print(a_list) print()
a_list = [1, 2, 3, 4, 5] del a_list[1] print(a_list) print()
print(a_list.pop()) print(a_list) print()
a_list = [1, 2, 3, 2, 4] a_list.remove(2) print(a_list)
|
1.2 列表元素的访问、计数、成员资格判断
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| aList = [1, 2, 3, 4, 5, 4, 9] print(aList[2]) aList[2] = "Hello" print(aList) print()
print("计数:") aList = [1, 2, 3, 4, 7, 7, 8] print(aList.count(7)) print(aList.count(0)) print()
aList = [1, 2, 3] print("成员判断:") print(3 in aList) print(5 in aList) print(5 not in aList)
|
1.3 切片
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| aList = [1, 2, 3, 4, 5, 4, 9]
print("切片:") print(aList[::]) print(aList[::-1]) print(aList) print(aList[2:6:2]) print(aList[3:])
aList[len(aList):] = [89] print(aList)
aList[:3] = [77, 88, 99] print(aList)
aList[:3] = [] print(aList)
aList = [1, 2, 3, 4, 5, 6] del aList[:3] print(aList)
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
| aList = [3, 5, 7] bList = aList[:]
print(aList) print(bList) print(aList == bList) print(aList is bList)
bList[0] = 99 print(aList) print(bList)
aList = [1, [88], 2] bList = aList[:]
bList[1].append(99) print(aList) print(bList)
print("下面的例子是深复制的例子") import copy aList = [1, [88], 2] bList = copy.deepcopy(aList)
print(aList == bList) print(aList is bList) print(aList) print(bList)
bList[1].append(99) print(aList) print(bList)
|
1.4 列表排序和逆序
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
| print("排序:") aList = [1, 2, 6, 15, 256, 51, 8]
aList.sort() print("sort()升序") print(aList) print()
aList.sort(reverse=True) print("sort()降序") print(aList) print()
aList.sort(key=lambda x: len(str(x))) print("sort()其他方式排序:转换为字符串后的长度排序") print(aList) print()
print("sorted()升序") print(sorted(aList))
print("sorted()降序") print(sorted(aList, reverse=True)) print()
aList = [1, 2, 6, 5, 2, 5, 8] aList.reverse() print(aList) print()
|
1 2 3 4 5 6 7 8 9
| aList = [3, 4, 5, 6, 7, 7, 8, 4, 6] newList = reversed(aList) print(newList)
print(aList) print(list(newList))
print(list(newList))
|
1. 5 用于序列操作的常用内置函数
any()用来测试序列或可迭代对象中是否存在等价于 True 的元素
all()用来测试序列或可迭代对象中是否所有元素都等价于 True
1 2 3 4 5 6 7 8
| print("any():") print(any([0, 1, 2])) print(any([0])) print()
print("all():") print(all([1, 2, 3, 4])) print(all([0, 1, 2, 3]))
|
sum():对数值型列表的元素进行求和运算,对于非数值型列表需要指定第二个参数,适用于元组、集合、range 对象、字典、map 对象、filter 对象等。
1 2 3 4 5 6 7 8 9 10
| a = { 1: 77, 2: 88, 3: 99 }
print(sum(a)) print(sum(a.values()))
print(sum([[1], [2], ["name"]], []))
|
zip()方法、enumerate()方法参考 python(一)
1.5 列表推导式
列表推导式语法
1
| [exp for variable in iterable if condition]
|
列表推导式使用非常简洁的方式来快速生成满足特定需求的列表。(非常简洁,以至于有时候很难看懂,应多看多敲)
几个例子
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| aList = [x*x for x in range(10)] print(aList) print() ''' 相当于 aList = [] for x in range(10): aList.append(x * x)
print(aList) '''
vec = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] print("使用列表推导式实现嵌套列表的平铺") print(vec) print([num for elem in vec for num in elem]) print()
print("在列表推导式中使用多个循环") print([(x, y) for x in range(3) for y in range(3)])
|
2. 元组
2.1 元组的创建和删除
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| myTuple = () print(myTuple)
myTuple = ('1', 'Hello', 2, True) print(myTuple)
myTuple = 1, 2, 3, True, "Hello" print(myTuple)
myTuple = (2) print(myTuple)
myTuple = tuple('Hello World!') print(myTuple)
del myTuple
|
2.2 元组和列表的区别
- 列表属于可变序列, 元组属于不可变序列
- 元组没有提供 append()、extend()、insert()和 remove()、pop()方法
- 元组不支持对元组元素进行 del 操作,只能用 del 命令删除整个元组
- 元组也支持切片操作,但只能通过切片来访问元组中的元素
- 元组的访问和处理速度比列表更快
元组属于不可变序列,其元素的值是不可改变的,但是元组中含有可变序列的话,可以通过调用可变序列的方法来改变可变序列的值。
1 2 3 4 5 6 7 8
| myTuple = (1, [77, 88], 8) print(myTuple)
myTuple[1].append(99) print(myTuple)
myTuple[1] += [111] print(myTuple)
|
2.3 序列解包
1 2 3 4 5 6 7
| x, y, z = 1, 2, 3 print(x, y, z)
myTuple = (True, "Hello", 88) (x, y, z) = myTuple
print(x, y, z)
|
序列解包用于列表和字典
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| a, b, c = [4, 5, 6] print(a, b, c)
s = { 'Hello': 1, 'World': 2, '!': 3, }
a, b, c = s print(a, b, c)
a, b, c = s.items() print(a, b, c)
a, b, c = s.values() print(a, b, c)
|
使用序列解包方便同时遍历多个序列。
1 2 3 4 5 6
| keys = ['a', 'b', 'c', 'd'] values = [1, 2, 3, 4]
for k, v in zip(keys, values): print(k, v)
|
可以加上一个或两个星号(*)进行序列解包
1 2 3 4 5 6 7 8
| print(*[1], *[2, 3], 4, *[5, 6, 7])
print({*range(4), 5, *(7, 8, 9)})
print({ 'x': 1, **{'y': 2} })
|
2.4 生成器表达式
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| g = ((i + 2)**2 for i in range(10)) print(g) print(list(g)) print(list(g))
g = ((i + 2)**2 for i in range(10)) print(g.__next__()) print(g.__next__())
print(next(g))
g = ((i + 2)**2 for i in range(10)) for i in g: print(i, end=' ')
|
3. 字典
3.1 字典的创建与删除
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
| mydict = { 'a': 1, 'b': 2 } print(mydict)
keys = ['a', 'b', 'c'] values = [1, 2, 3] print(dict(zip(keys, values)))
mydict = dict() print(mydict) print(type(mydict))
mydict = {} print(mydict) print(type(mydict))
mydict = dict(name='clz', age=21, sex='male', address='QQ') print(mydict)
del mydict['age'] print(mydict)
print('----pop()----------') print(mydict.pop('sex')) print(mydict)
print('----popitem()------') print(mydict.popitem()) print(mydict)
mydict.clear() print(mydict)
|
3.2 字典元素的读取
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| mydict = dict(name='clz', age=21, sex = 'male')
print(mydict['name'])
print(mydict.get('age'))
print(mydict.keys())
print(mydict.values())
print(mydict.items())
for key, value in mydict.items(): print(key, value, sep=':')
|
3.3 字典的添加与修改
1 2 3 4 5 6 7 8 9 10 11
| mydict = dict(name='clz', age=21, sex = 'male')
mydict['name'] = 'czh' print(mydict)
mydict['address'] = 'QQ' print(mydict)
mydict2 = dict(name='czh', age=22, sex = 'male', haha = 'Hello') mydict.update(mydict2) print(mydict)
|
4. 集合
特点:没有重复的元素
4.1 集合的创建和删除
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| myset = {1, 2, 1, 4, 5, 2} print(myset)
myset = set([1, 2, 3, 5, 2, 3]) print(myset)
myset = set() print(myset)
myset.add(3) print(myset) myset.add(2) myset.add(1) print(myset)
myset.pop() print(myset)
myset.remove(3) print(myset)
|
4.2 集合运算
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| aset = {1, 2, 3, 4, 5, 6} bset = {3, 4, 5, 6, 7, 8}
print(aset | bset)
print(aset & bset)
print(aset - bset)
print(aset ^ bset)
aset = {1, 2, 3} bset = {1, 2, 4} print(bset < aset) print(bset == aset) print(bset > aset)
cset = {1, 2, 3, 5} print(aset < cset)
|
5. 复杂数据结构
5.1 堆
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
| import heapq import random data = list(range(10)) random.shuffle(data) print(data)
heap = [] for n in data: heapq.heappush(heap, n)
print(heap)
heapq.heappush(heap, 0.5) print(heap) print(heapq.heappop(heap)) print(heap)
myheap = [1, 2, 3, 4, 7, 4, 6, 8, 3, 9, 434] heapq.heapify(myheap) print(myheap)
heapq.heapreplace(myheap, 6) print(myheap)
print(heapq.nlargest(4, myheap)) print(heapq.nsmallest(5, myheap))
|
5.2 队列
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
| import queue q = queue.Queue()
q.put(1) q.put(5) q.put(3) print(q.queue)
print(q.get()) print(q.queue)
''' 后进先出队列 ''' LiFoQueue = queue.LifoQueue(5) LiFoQueue.put(1) LiFoQueue.put(2) LiFoQueue.put(3)
print(LiFoQueue.queue) print(LiFoQueue.get()) print(LiFoQueue.queue)
''' 优先级队列 优先级队列,自动依照元素的权值排列。权值最高者排在最前面 没有去权值时,则按建堆来排列 ''' PriQueue = queue.PriorityQueue(5) PriQueue.put(3) PriQueue.put(5) PriQueue.put(1) PriQueue.put(7) print(PriQueue.queue)
print(PriQueue.get()) print(PriQueue.queue)
|
5.3 栈
可以使用列表来实现栈,append()方法用于实现入栈操作,pop()方法用于实现出栈操作。
1 2 3 4 5 6 7 8 9 10 11 12 13
| mystack = [] mystack.append(1) mystack.append(3) mystack.append(5)
print(mystack) print(mystack.pop()) print(mystack)
mystack.pop() print(mystack) mystack.pop() print(mystack)
|
用列表来实现栈不足:1. 当列表为空时,再执行 pop()会抛出异常; 2. 无法限制栈的大小
可以自己自定义栈结构来实现。
5.4 链表
可以使用列表来实现链表
1 2 3 4 5 6 7 8 9 10
| linkTable = [] linkTable.append(1) linkTable.append(3) print(linkTable)
linkTable.insert(1, 2) print(linkTable)
linkTable.remove(linkTable[2]) print(linkTable)
|
5.5 二叉树
自定义二叉树
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
| class BinaryTree: def __init__(self, value): self.__left = None self.__right = None self.__data = value
def buildLeftChild(self, value): if self.__left: print('左孩子已经存在') else: self.__left = BinaryTree(value) return self.__left
def buildRightChild(self, value): if self.__right: print('右孩子已经存在') else: self.__right = BinaryTree(value) return self.__right
def show(self): print(self.__data)
def preOrder(self): print(self.__data) if self.__left: self.__left.preOrder() if self.__right: self.__right.preOrder()
def inOrder(self): if self.__left: self.__left.inOrder() print(self.__data) if self.__right: self.__right.inOrder()
def postOrder(self): if self.__left: self.__left.postOrder() if self.__right: self.__right.postOrder() print(self.__data)
|
选择结构
之前没有学到的特别用法
1 2 3 4 5 6 7 8 9 10 11 12
| x = 5 if 2 > 1 else 6 print(x)
''' if 2 > 1: x = 5 else: x = 6
print(x) '''
|