python基础-max,min,sorted高级玩法

max,min,sorted:最大,最小,排序的高级玩法

def max(*args, key=None): # known special case of max
    """
    max(iterable, *[, default=obj, key=func]) -> value
    max(arg1, arg2, *args, *[, key=func]) -> value

def min(*args, key=None): # known special case of min
    """
    min(iterable, *[, default=obj, key=func]) -> value
    min(arg1, arg2, *args, *[, key=func]) -> value

def sorted(*args, **kwargs): # real signature unknown
    """
    Return a new list containing all items from the iterable in ascending order.
    
    A custom key function can be supplied to customize the sort order, and the
    reverse flag can be set to request the result in descending order.
    """
    pass

可以看出,则几个函数第一个参数都是可变长度参数——列表,元祖,集合,字典

初级:

a1=max({1,2,3})
print(a1)
a2=max({'z1':1,'2':2,'c':4})#字典默认比较key
print(a2)

 

给定一个字典,判断字典的value最大值并输出,输出value的同时并同时输出对应的key

需要使用zip函数

dict_1={'z1':1,'2':2,'c':4}
a=zip(dict_1.values(),dict_1.keys()) #zip函数将可迭代对象重新组成元组
print(a)
#print(list(a))
print(max(a))#迭代器list后,再max会报错

 

l=[
    (5,'a',00),
    (3,'b','ab'),
    (9,'c','aaa')
]
print(max(l)) #先比较每个元素的第一位

 

终极版本-max/min

#求age最大的元素
dict_people=[
    {'name':'alex','age':1000},
    {'name':'wupeiqi','age':800},
    {'name':'yuhao','age':900},
    {'name':'linhaifeng','age':200}
]
#查看源文件可知,max每次for循环的是元素,而max有key,可为func,所以对元素可进行func操作
max_peopel=max(dict_people,key=lambda x:x['age'])
# x为func函数处理的元素,x['age']返回值为age对应的value值
print(max_peopel)

终极版本-sorted,同max

#根据age排序
dict_people=[
    {'name':'alex','age':1000},
    {'name':'wupeiqi','age':800},
    {'name':'yuhao','age':900},
    {'name':'linhaifeng','age':200}
]
res=sorted(dict_people,key=lambda x:x['age']) # x为每个元素
print(res)

posted @ 2020-11-25 17:20  枫叶学python  阅读(405)  评论(0)    收藏  举报