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 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
| "yahoo!" if 3 > 2 else 2
other_set = {3, 4, 5, 6} filled_set & other_set
filled_set | other_set
{1, 2, 3, 4} - {2, 3, 5}
None
"etc" is None None is None
0 == False "" == False
def varargs(*args): return args
varargs(1, 2, 3)
def keyword_args(**kwargs): return kwargs
keyword_args(big="foot", loch="ness")
def all_the_args(*args, **kwargs): print args print kwargs """ all_the_args(1, 2, a=3, b=4) prints: (1, 2) {"a": 3, "b": 4} """
def create_adder(x): def adder(y): return x + y return adder
add_10 = create_adder(10) add_10(3)
add_10 = create_adder(10) add_10(3)
(lambda x: x > 2)(3)
map(add_10, [1, 2, 3]) map()传入的第一个参数是f,即函数对象本身
再看reduce的用法。reduce把一个函数作用在一个序列[x1, x2, x3...]上,这个函数必须接收两个参数,reduce把结果继续和序列的下一个元素做累积计算,其效果就是:
reduce(f, [x1, x2, x3, x4]) = f(f(f(x1, x2), x3), x4)
filter(lambda x: x > 5, [3, 4, 5, 6, 7])
[add_10(i) for i in [1, 2, 3]] [x for x in [3, 4, 5, 6, 7] if x > 5]
|