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 arrivaldeque(['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)]