![fa412981aa446f7c3a1fe1792f9efa51.png](https://i-blog.csdnimg.cn/blog_migrate/493e8b69efacf312f46454130a37c837.jpeg)
map filter函数
def is_even(n):
return n%2 == 0
print(list(map(is_even, range(10))))
print([is_even(i) for i in range(10)])
print(list(map(is_even, filter(lambda n: n>5, range(10)))))
print([is_even(i) for i in range(10) if i > 5])
输出
[True, False, True, False, True, False, True, False, True, False]
[True, False, True, False, True, False, True, False, True, False]
[True, False, True, False]
[True, False, True, False]
reduce函数
from functools import reduce
print(reduce(lambda x,y: x+y, range(100)))
print(sum(range(100)))
输出
4950
4960
all和any
flag_1 = [1,1,1,1,1,1]
flag_2 = [1,0,1,0,0,1]
print(all(flag_1), all(flag_2))
print(any(flag_1), any(flag_2))
输出
True False
True True
匿名函数
fruits = ['apple', 'banana', 'strawberry', 'cherry']
print(sorted(fruits, key= lambda word: word[::-1]))
输出
['banana', 'apple', 'strawberry', 'cherry']
把函数作为参数传递
def factorial(n):
'''returns n!'''
return 1 if n<2 else n*factorial(n-1)
print(factorial(42))
print(factorial.__doc__)
print(type(factorial))
fact = factorial
print(fact)
print(fact(5))
for i in map(factorial, range(11)):
print(i)
for i in map(lambda x: x**2, [1,2,3,4,5]):
print(i)
print(list(map(factorial, range(11))))
#高阶函数
fruits = ['apple', 'banana', 'strawberry', 'cherry']
print(sorted(fruits, key=len))
def reverse(word):
return word[::-1]
word = 'apple'
print(reverse(word))
print(sorted(fruits, reverse))
输出
1405006117752879898543142606244511569936384000000000
returns n!
<class 'function'>
<function factorial at 0x1099b9440>
120
1
1
2
6
24
120
720
5040
40320
362880
3628800
1
4
9
16
25
[1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880, 3628800]
['apple', 'banana', 'cherry', 'strawberry']
elppa
['banana', 'apple', 'strawberry', 'cherry']
可调用对象
import random
class BingoCage:
def __init__(self,items):
self._items = items
random.shuffle(self._items)
def pick(self):
try:
return self._items.pop()
except IndexError:
raise LookupError('pick from empty BingoCage')
def __call__(self):
return self.pick()
bingo = BingoCage([0,1,2])
print(bingo.pick())
print(bingo())
print(bingo())
print(callable(bingo))
输出
1
0
2
True