list主要的函数:
- 创建List
- >>> l = [1,(1,2),2,"3"]
- >>> print l
- [1, (1, 2), 2, '3']
- 添加
list.append(x) #增加一个元素到列表中,等同于list[len(list):] = [x]
list.extend(L) #增加一个list到列表中,等同于list[len(list):] = L
list.insert(i, x) #在指定位置插入元素x
- 更新
没有合适的函数,可以使用下标取值,并赋值。比如:l[1] = 1.5
- 删除
list.remove(x) #删除第一个为x元素, 没有元素x,就报错
list.pop([i]) #在给定位置i 删除list,如果没有i,则删除list最后一个元素
list[i:j] #解释参考取值部分,可以用于插值
- 取值
list.index(x) # 取第一个为x的元素位置,如果没有报错
list[i] #取i位置的元素
list[i:j] #取>=i&& < j的列表片段, 如果i或者j为空,则表示取开始到j的片段列表或者i到结尾的列表片段。 如果j=-1,表示i到倒数第一个元素的列表片段(相当于j = len(list) -1)。
- 计算个数
list.count(x) #统计x在列表中的个数,没有为0
- 排序
list.sort(cmp=None, key=None, reverse=false) #排序
- 逆序
list.reverse() #逆序
使用list仿造stack
>>> stack = [3, 4, 5] >>> stack.append(6) >>> stack.append(7) >>> stack [3, 4, 5, 6, 7] >>> stack.pop() 7 >>> stack [3, 4, 5, 6] >>> stack.pop() 6 >>> stack.pop() 5 >>> stack [3, 4]
使用list仿造queue
直接使用list删除第一个元素的效率比较低,因为需要移动元素。
>>> from collections import deque >>> queue = deque(["Eric", "John", "Michael"]) >>> queue.append("Terry") # Terry arrives >>> queue.append("Graham") # Graham arrives >>> queue.popleft() # The first to arrive now leaves 'Eric' >>> queue.popleft() # The second to arrive now leaves 'John' >>> queue # Remaining queue in order of arrival deque(['Michael', 'Terry', 'Graham'])
三个函数有意思的函数介绍
filter #过滤满足条件的结构,返回listmap() #计算函数的值,组成 listreduce() #两两计算函数的值,返回元素值。比如:reduce(add,[1,2,3,4]) 1+2 +3 + 4>>> def f(x): return x % 3 == 0 or x % 5 == 0 ... >>> filter(f, range(2, 25)) [3, 5, 6, 9, 10, 12, 15, 18, 20, 21, 24] >>> def cube(x): return x*x*x ... >>> map(cube, range(1, 11)) [1, 8, 27, 64, 125, 216, 343, 512, 729, 1000] >>> seq = range(8) >>> def add(x, y): return x+y ... >>> map(add, seq, seq) [0, 2, 4, 6, 8, 10, 12, 14] >>> def add(x,y): return x+y ... >>> reduce(add, range(1, 11)) 55
list理解
sequares = [x**2 for x in range(10)] #等同于 squares = map(lambda x: x**2, range(10)) >>> squares [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] >>> [(x, y) for x in [1,2,3] for y in [3,1,4] if x != y] [(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]
嵌套list理解(复杂)
>>> matrix = [ ... [1, 2, 3, 4], ... [5, 6, 7, 8], ... [9, 10, 11, 12], ... ] >>> >>> [[row[i] for row in matrix] for i in range(4)] [[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]] #等同于 >>> >>> transposed = [] >>> for i in range(4): ... transposed.append([row[i] for row in matrix]) ... >>> transposed [[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]] #等同于 >>> >>> transposed = [] >>> for i in range(4): ... # the following 3 lines implement the nested listcomp ... transposed_row = [] ... for row in matrix: ... transposed_row.append(row[i]) ... transposed.append(transposed_row) ... >>> transposed [[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]] #也可以使用zip函数 >>> >>> zip(*matrix) [(1, 5, 9), (2, 6, 10), (3, 7, 11), (4, 8, 12)]