fly00love 2020-03-05
在学习完列表和元组的基础知识后,做到一个题:
求出列表中频次出现最多的元素。
学习到了python内置函数max的用法 其参数key的用法 匿名函数lamda的用法
max()方法返回给定参数的最大值,参数值可为序列。
print ("max(80, 100, 1000) : ", max(80, 100, 1000)) print ("max(-20, 100, 400) : ", max(-20, 100, 400)) print ("max(-80, -20, -10) : ", max(-80, -20, -10)) print ("max(0, 100, -400) : ", max(0, 100, -400))
输出为:
max(80, 100, 1000) : 1000 max(-20, 100, 400) : 400 max(-80, -20, -10) : -10 max(0, 100, -400) : 100
key参数的解释:
key(optional): key function where each argument is passed, and comparison is performed baased on its return value
简而言之,就是key中传递的是一个参数,此时max会根据每个传入参数后的返回值进行比较。返回值为key中的参数值
以字典为例:
#the key whose value is the largest square = {2: 4, -3: 9, -1: 1, -2: 4} key2 = max(square, key = lamda k: square[k]) print("The key with the largest value: ",key2) #-3 print("The largest value: ",square[key2])#9
lambda arguments: expression
# Python code to illustrate cube of a number # showing difference between def() and lambda(). def cube(y): return y*y*y; g = lambda x: x*x*x print(g(7)) #343 print(cube(7)) #343
def mode(lst): if lst is None or len(lst) == 0: return None return max(lst, key = lambda k: lst.count(k)) #调用mode lst = [1, 3, 3, 2, 1, 1, 2] r = mode(lst) print(r) #output : 1
f = lambda x, y, z: x + y + z # returns a function that can optionally be assigned a name. def func: