##########高阶函数############
# 高阶函数:
变量可以指向函数,函数的参数能接收变量,那么一个函数就可以接收另
一个函数作为参数,这种函数就称之为高阶函数。
- 实参是一个函数名;
- 函数的返回值是一个函数;
# 函数本身也可以赋值给变量,即:变量可以指向函数。
print(abs(-10))
f = abs
print(f(-10))# 传递的参数包含函数名.
def fun(x,y, f):
return f(x), f(y)print(fun(-10, 34, abs))
#内置高阶函数
1.map函数
map() 函数接收两个参数,一个是函数,一个是序列, map 将传入的函数依
次作用到序列的每个元素,并把结果作为新的 list 返回。
eg:对于序列求绝对值
print(list(map(abs, [-1, 3, -4, -5]))) print([abs(i) for i in [-1,3,-4,-5]])
2.reduce函数
reduce 把一个函数作用在一个序列[x1, x2, x3...]上,这个函数必须接
收两个参数,reduce 把结果继续和序列的下一个元素做累积计算。
eg:10!的阶乘
from functools import reduce def multi(x, y): return x * y # [1,2,3] ====> multi(multi(1,2), 3) print(reduce(multi, range(1, 4)))
3.filter函数
filter() 也接收一个函数和一个序列。和 map() 不同的时,
filter() 把传入的函数依次作用于每个元素,然后根据返回值是 True
还是 False 决定保留还是丢弃该元素。
eg:拿出1~100之间所有的素数
def isPrime(num): for i in range(2, num): if num % i == 0: return False else: return True print(list(filter(isPrime, range(2, 101))))
4.sorted函数
可以对数据类型进行排序
# 1. li.sort()和sorted()两种方法的区别?
1). 列表里面提供了sort方法, 其他数据结构没有.sorted方法可以对任何可迭代对象排序.
2).sort方法支持原地排序(变量排序后, 变量本身改变), sorted排序后返回一个新的列表,并不改变原变量的内容.
# 2.默认sort和sorted方法由小到大进行排序, reverse=True时, 由大到小进行排序.
li = [1, 2, 6, 21324, 67, 2, 23] print(sorted(li, reverse=True)) print(li) li.sort(reverse=True) print(li)
# 3. 对于列表里面嵌套列表进行排序.
info = [ # 商品名称 商品数量 商品价格 ('apple3', 200, 32), ('apple4', 40, 12), ('apple1', 40, 2), ('apple2', 1000, 23), ] print(sorted(info)) def sorted_by_count(x): # x = ('apple3', 200, 32) return x[1] def sorted_by_price(x): return x[2] def sorted_by_count_price(x): return x[1], x[2] print(sorted(info, key=sorted_by_count)) # 按照商品的数量进行排序, key代表排序的关键字 print(sorted(info, key=sorted_by_price)) # 按照商品的价格进行排序, key代表排序的关键字 print(sorted(info, key=sorted_by_count_price)) # 先按照商品数量由小到大进行排序, 如果商品数量一致, 则按照商品价格由小到大进行排序.
# 4. 对于字典里面嵌套字典进行排序
d = { '003':{ 'name':'apple1', 'count':100, 'price':10 }, '002': { 'name': 'apple1', 'count': 200, 'price': 2 }, } print(d.items()) print(sorted(d.items(), key=lambda x: x[1]['count'])) #lambda 是匿名函数 print(sorted(d.items(), key=lambda x: x[1]['price']))
# 匿名函数
当我们在传入函数时,有些时候,不需要显式地定义函数,直接传入匿名函数更方便。
关键字 lambda 表示匿名函数,冒号前面的 x 表示函数参数
匿名函数有只能有一个表达式,不用写 return ,返回值就是该表达式的结果。
因为匿名函数没有名字,不必担心函数名冲突。 此外,匿名函数也是一个函数对
象,也可以把匿名函数赋值给一个变量,再利用变量来调用该函数;
也可以把匿名函数作为返回值返回
eg:奇偶排序
问题描述: 有一个整数列表(10个元素), 要求调整元素顺序, 把所有的奇数放在前面, 偶数放在后面,
import random li = [random.randint(1, 10) for i in range(10)] li.sort() print(li) print(sorted(li, key=lambda x: 1 if x % 2 == 0 else 0)) print(sorted(li, key=lambda x: x%2==0))
#max及min
d = { 'user2':{1,2,4,6}, 'user3':{2,2,9,6}, 'user4':{3,2,5,6}, } # 找出user3用户兴趣最相似的 # user1喜欢的电影 film = {1,2,67} maxfilms = max(d.values(), key=lambda x: x & film ) # 找出字典中跟user1最相似的(即跟user1喜欢的电影最多的) print(maxfilms) print("推荐给user1的电影:", maxfilms - film)
#############小拓展##############
1. 如何随机生成验证码, 快速生成内推码。 import random import string code_str = string.ascii_letters + string.digits print(code_str) def gen_code(len=4): # code = '' # # 字母或者数字组 # for i in range(len): # new_s = random.choice(code_str) # 'a' # code += new_s return "".join(random.sample(code_str, len)) print([gen_code(len=6) for i in range(10)]) print({gen_code(len=6) for j in range(10)})
2.凯撒加密
import string # abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ # defghijklmnopqrstuvwxyzabc DEFGHIJKLMNOPQRSTUVWXYZABC # 凯撒加密---加密算法的实现 def kaisacrypt(text='hello', k=3): # 对原有小写字母向右移动k位 lower = string.ascii_lowercase[k:] + string.ascii_lowercase[:k] upper = string.ascii_uppercase[k:] + string.ascii_uppercase[:k] # 用于创建字符串映射的转换表'hello' table = str.maketrans(string.ascii_letters, lower+upper) # 根据转换表去转换对应的字符 return text.translate(table) def check(text): """ 思路: 测试文本中是否存在至少两个最常见的英文单词, 如果有, 则代表破解成功. """ mostCommonWords = ('the', 'is', 'to', 'not', 'have', 'than', 'for', 'ok', 'and' ) return len([1 for word in mostCommonWords if word in text])>2 # 暴力破解 def bruteForce(text): for i in range(26): # 1,2,3,4,5 t = kaisacrypt(text, -i) if check(t): print(i) print(t) break text = "If not to the sun for smiling, warm is still in the sun there, but wewill laugh more confident calm; if turned to found his own shadow, appropriate escape, the sun will be through the heart,warm each place behind the corner; if an outstretched palm cannot fall butterfly, then clenched waving arms, given power; if I can't have bright smile, it will face to the sunshine, and sunshine smile together, in full bloom." cryptStr = kaisacrypt(text=text, k=18) print(cryptStr) bruteForce(cryptStr)