1. 程式人生 > >lambda ,map,zip,max,min

lambda ,map,zip,max,min

salaries={
    'a':3000,
    'b':10000,
    'c':1000,
    'd':2000
}
res=max(salaries)      #dict 預設傳字典的key比較大小
print(res)
d

res=max(salaries,key=lambda k:salaries[k])       #lambda 返回 value ,通過value 比較大小
print(res) #最後得到b的結果最大,所以返回b
b

通過zip 使key,value換一下位置:

res=zip(salaries.values(),salaries.keys())
print(list(res)) # list 後 res 迭代器裡面空了,再max(res)報錯

[(3000, 'a'), (10000, 'b'), (1000, 'c'), (2000, 'd')]

 max(res)

res=zip(salaries.values(),salaries.keys())
# print(list(res)) 迭代器只能取一次
ret=max(res)
print(ret)

(10000, 'b')

zip

a=[1,2,3]
b=[4,5,6]
c=zip(a,b)
print(list(c))

[(1, 4), (2, 5), (3, 6)]


a=[1,2,3]
b=[4,5,]
c=zip(a,b)
print(list(c))
[(1, 4), (2, 5)]

map

re=map(lambda x:x+1,[1,2,3])           #map(func,itersobj)
print(re)
print(list(re))

<map object at 0x02113190>
[2, 3, 4]