# Python之函数式编程

1.map：

```def OrderName(name):
g = lambda Newname:Newname[0].upper() + Newname[1:].lower()
return g(name)

print map(OrderName, lst)```

2.reduce:

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

```def prod(lst):
return reduce(lambda x, y: x*y, lst)

lst = [1,2,3,4,5,6]
print prod(lst)```

3.filter

```def mDel(num):
if num == 1:
return True
for i in range(2, num):
if num % i == 0:
return True
return False

print filter(mDel, range(1, 101))```

## 考虑 1 不是 素数 也不是合数 所以应该保留 1 ##

4.sorted

```def myCmp(s1, s2):
u1 = s1.upper()
u2 = s2.upper()
if u1 > u2:
return 1
elif u1 == u2:
return 0
elif u1 < u2:
return -1

lst = [‘bob‘, ‘about‘, ‘Zoo‘, ‘Credit‘]
print sorted(lst, myCmp)```

```def lazy_sum(*args):
def sum():
ax = 0
for n in args:
ax = ax + n
return ax
return sum```

```>>> f = lazy_sum(1, 3, 5, 7, 9)
>>> f
<function sum at 0x10452f668>```

```>>> f()
25```

```def f(x):
return x * x```

```>>> import functools
>>> int2 = functools.partial(int, base=2)
>>> int2(‘1000000‘)
64
>>> int2(‘1010101‘)
85```

`functools.partial`的作用就是，把一个函数的某些参数给固定住（也就是设置默认值），返回一个新的函数，调用这个新函数会更简单。

Python之函数式编程

(0)
(0)