[Python] 函数
2021-02-16 06:21
标签:bsp next import ini 重复 code init class 计算 高阶函数 嵌套函数 闭包(closure) 匿名函数 可调用对象 函数式编程 [Python] 函数 标签:bsp next import ini 重复 code init class 计算 原文地址:https://www.cnblogs.com/cxc1357/p/12708173.html
1 def nth_power(exponent):
2 def exponent_of(base):
3 return base ** exponent
4 return exponent_of
5
6 square = nth_power(2)
7 cube = nth_power(3)
8
9 print(square(2))
10 print(cube(3))
1 [(lambda x:x*x)(x) for x in range(10)]
1 l = [(1,20),(3,0),(9,10),(2,-1)]
2 l.sort(key=lambda x:x[1])
3 print(l)
1 import random
2
3 class BingoCage:
4 def __init__(self, items):
5 self._items = list(items)
6 random.shuffle(self._items)
7 def pick(self):
8 try:
9 return self._items.pop()
10 except IndexError:
11 raise LookupError(‘pick from empty BingoCage‘)
12 def __call__(self):
13 return self.pick()
14
15 bingo = BingoCage(range(5))
16 bingo.pick()
1 # map函数
2 def factorial(n):
3 return 1 if n else n * factorial(n-1)
4
5 fact = factorial
6 list(map(fact,range(10)))
1 list(map(fact, filter(lambda n:n%2,range(6))))
1 from functools import reduce
2 reduce(lambda x, y: x+y, [1,2,3,4,5])
上一篇:3.K均值算法