2 Star 3 Fork 3

celaraze / learning-python

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
13.高阶函数.py 1.03 KB
一键复制 编辑 原始数据 按行查看 历史
famio 提交于 2019-12-29 23:47 . 高阶函数
# 函数可以直接赋值给变量,也就是变量可以指向函数
from functools import reduce
a = abs
print(a(-10))
# 传入函数
def add(a, b, f):
return f(a)+f(b)
print(add(1, 2, abs))
# map和reduce
def foo(n):
return n * n
result = map(foo, [1, 2, 3, 4, 5, 6, 7, 8, 9])
# 通过list方法可以遍历列表
print(list(result))
def addTwo(a, b):
return a+b
result = reduce(addTwo, [1, 2, 3, 4, 5, 6, 7])
print(result)
# filter用于过滤序列
def isDouble(number):
return number % 2 == 1
print(list(filter(isDouble, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])))
# sorted排序
l = sorted([55, 72, 1, 2, -19])
print(l)
# sorted排序通过key来实现,这里使用abs绝对值函数
l = sorted([55, 72, 1, 2, -19], key=abs)
print(l)
# sorted排序用在字符串上,默认是根据ASCII表进行比对
l = ['Zoo', 'Tom', 'About', 'more']
print(sorted(l))
# sorted排序用在字符串上,key选择忽视大小写
print(sorted(l, key=str.lower))
# 反向排序
print(sorted(l, key=str.lower, reverse=True))
Python
1
https://gitee.com/celaraze/learning-python.git
git@gitee.com:celaraze/learning-python.git
celaraze
learning-python
learning-python
master

搜索帮助