# 函数

def calc(*numbers):
sum = 0
for n in numbers:
sum = sum + n * n
return sum

>>> calc(1, 2)

python还允许在list和tuple前加*号，将其转化为可变参数传入。

>>> nums = [1, 2, 3]
>>> calc(*nums)

def person(name, age, **kw):
>>> person('Adam', 45, gender='M', job='Engineer')
name: Adam age: 45 other: {'gender': 'M', 'job': 'Engineer'}

>>> person('Michael', 30)

>>> extra = {'city': 'Beijing', 'job': 'Engineer'}
>>> person('Jack', 24, **extra)

def person(name, age, *, city, job):
>>> person('Jack', 24, city='Beijing', job='Engineer')

def person(name, age, *args, city, job):

map()将传入的函数依次作用到序列的每个元素，并将结果作为新的Interator返回

>>> 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()把一个函数作用在一个序列上，这个函数必须接受两个参数，reduce()把结果继续和序列的下一个元素进行累计运算

reduce(f, [x1, x2, x3, x4]) = f(f(f(x1, x2), x3), x4)


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]

sorted函数也是高阶函数，除了普通的排序，它还可以接受一个key函数来实现自定义排序

>>> sorted([36, 5, -12, 9, -21], key=abs)
[5, 9, -12, -21, 36]

>>> sorted(['bob', 'about', 'Zoo', 'Credit'], key=str.lower)
['about', 'bob', 'Credit', 'Zoo']

>>> sorted(['bob', 'about', 'Zoo', 'Credit'], key=str.lower, reverse=True)
['Zoo', 'Credit', 'bob', 'about']

def f(x):
return x * x   = lambda x : x * x

def build(x, y):
return lambda: x * x + y * y