Slice(切片)
>>> L = [‘Michael‘, ‘Sarah‘, ‘Tracy‘, ‘Bob‘, ‘Jack‘] >>> L[0:3] [‘Michael‘, ‘Sarah‘, ‘Tracy‘] >>> L[:3] [‘Michael‘, ‘Sarah‘, ‘Tracy‘] >>> L[1:3] [‘Sarah‘, ‘Tracy‘] >>> L[-2:] [‘Bob‘, ‘Jack‘] >>> L[-2:-1] [‘Bob‘] >>> L = list(range(100)) >>> L [0, 1, 2, 3, ..., 99] >>> L[:] [0, 1, 2, 3, ..., 99] >>> L[:10:2] [0, 2, 4, 6, 8] >>> L[::5] [0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95]
>>> (0, 1, 2, 3, 4, 5)[:3]
(0, 1, 2)
>>> ‘ABCDEFG‘[:3] ‘ABC‘ >>> ‘ABCDEFG‘[::2] ‘ACEG‘
For ... in ...(迭代)
默认情况下,dict迭代的是key。如果要迭代value,可以用for value in d.values()
,如果要同时迭代key和value,可以用for k, v in d.items()。
>>> d = {‘a‘: 1, ‘b‘: 2, ‘c‘: 3} >>> for key in d: ... print(key) ... a c b
>>> for ch in ‘ABC‘: ... print(ch) ... A B C
判断可迭代对象
>>> from collections import Iterable >>> isinstance(‘abc‘, Iterable) # str是否可迭代 True >>> isinstance([1,2,3], Iterable) # list是否可迭代 True >>> isinstance(123, Iterable) # 整数是否可迭代 False
>>> for i, value in enumerate([‘A‘, ‘B‘, ‘C‘]): ... print(i, value) ... 0 A 1 B 2 C
>>> for x, y in [(1, 1), (2, 4), (3, 9)]: ... print(x, y) ... 1 1 2 4 3 9
列表生成式
>>> list(range(1, 11)) [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] >>> [x * x for x in range(1, 11)] [1, 4, 9, 16, 25, 36, 49, 64, 81, 100] >>> [x * x for x in range(1, 11) if x % 2 == 0] [4, 16, 36, 64, 100] >>> [m + n for m in ‘ABC‘ for n in ‘XYZ‘] [‘AX‘, ‘AY‘, ‘AZ‘, ‘BX‘, ‘BY‘, ‘BZ‘, ‘CX‘, ‘CY‘, ‘CZ‘] >>> d = {‘x‘: ‘A‘, ‘y‘: ‘B‘, ‘z‘: ‘C‘ } >>> [k + ‘=‘ + v for k, v in d.items()] [‘y=B‘, ‘x=A‘, ‘z=C‘] >>> L = [‘Hello‘, ‘World‘, ‘IBM‘, ‘Apple‘] >>> [s.lower() for s in L] [‘hello‘, ‘world‘, ‘ibm‘, ‘apple‘]
生成器
>>> g = (x * x for x in range(10)) >>> g <generator object <genexpr> at 0x1022ef630>
>>> next(g) 0 >>> next(g) 1 >>> next(g) 4 >>> next(g) 9 >>> next(g) 16 >>> next(g) 25 >>> next(g) 36 >>> next(g) 49 >>> next(g) 64 >>> next(g) 81 >>> next(g) Traceback (most recent call last): File "<stdin>", line 1, in <module> StopIteration
generator保存的是算法,每次调用next(g)
,就计算出g
的下一个元素的值,直到计算到最后一个元素,没有更多的元素时,抛出StopIteration
的错误。
>>> g = (x * x for x in range(10)) >>> for n in g: ... print(n) ... 0 1 4 9 16 25 36 49 64 81
如果一个函数定义中包含yield
关键字,那么这个函数就不再是一个普通函数,而是一个generator。generator的函数,在每次调用next()
的时候执行,遇到yield
语句返回,再次执行时从上次返回的yield
语句处继续执行。
def odd(): print(‘step 1‘) yield 1 print(‘step 2‘) yield(3) print(‘step 3‘) yield(5) >>> o = odd() >>> next(o) step 1 1 >>> next(o) step 2 3 >>> next(o) step 3 5 >>> next(o) Traceback (most recent call last): File "<stdin>", line 1, in <module> StopIteration
map
>>> def f(x): ... return x * x ... >>> r = map(f, [1, 2, 3, 4, 5, 6, 7, 8, 9]) >>> list(r) [1, 4, 9, 16, 25, 36, 49, 64, 81]
reduce
>>> from functools import reduce >>> def add(x, y): ... return x + y ... >>> reduce(add, [1, 3, 5, 7, 9]) 25
>>> from functools import reduce >>> def fn(x, y): ... return x * 10 + y ... >>> reduce(fn, [1, 3, 5, 7, 9]) 13579
filter
def is_odd(n): return n % 2 == 1 list(filter(is_odd, [1, 2, 4, 5, 6, 9, 10, 15])) # 结果: [1, 5, 9, 15]
def not_empty(s): return s and s.strip() list(filter(not_empty, [‘A‘, ‘‘, ‘B‘, None, ‘C‘, ‘ ‘])) # 结果: [‘A‘, ‘B‘, ‘C‘]
sorted
>>> sorted([36, 5, -12, 9, -21])
[-21, -12, 5, 9, 36]
>>> sorted([36, 5, -12, 9, -21], key=abs)
[5, 9, -12, -21, 36]
>>> sorted([‘bob‘, ‘about‘, ‘Zoo‘, ‘Credit‘]) [‘Credit‘, ‘Zoo‘, ‘about‘, ‘bob‘]
>>> sorted([‘bob‘, ‘about‘, ‘Zoo‘, ‘Credit‘], key=str.lower) [‘about‘, ‘bob‘, ‘Credit‘, ‘Zoo‘]
L = [(‘Bob‘, 75), (‘Adam‘, 92), (‘Bart‘, 66), (‘Lisa‘, 88)] list(sorted(L,key=lambda x :x[1]))
闭包
def count(): fs = [] for i in range(1, 4): def f(): return i*i fs.append(f) return fs f1, f2, f3 = count() >>> f1() 9 >>> f2() 9 >>> f3() 9
def count(): def f(j): def g(): return j*j return g fs = [] for i in range(1, 4): fs.append(f(i)) # f(i)立刻被执行,因此i的当前值被传入f() return fs >>> f1, f2, f3 = count() >>> f1() 1 >>> f2() 4 >>> f3() 9
匿名函数 lambda
只能有一个表达式,不用写return
,返回值就是该表达式的结果。
>>> f = lambda x: x * x >>> f <function <lambda> at 0x101c6ef28> >>> f(5) 25 def build(x, y): return lambda: x * x + y * y
装饰器
代码运行期间动态增加功能的方式,称之为“装饰器”(Decorator)。
偏函数
>>> import functools >>> int2 = functools.partial(int, base=2) >>> int2(‘1000000‘) 64 >>> int2(‘1010101‘) 85 >>> int2(‘1000000‘, base=10) 1000000
no yuchuang.just shuxishuxi.