Python3函數(一)

1.返回值

 當函數返回值爲多個時,可以用多個變量來接收,或自動組裝爲元組

def fun(a,b):
    a,b=11,12
    return a,b
print(fun(1,2))

2.三個大數據常用的函數

 1>map(func, *iterables)

自動遍歷序列各元素後,執行單個元素的對應操作後返回結果   

foo=[2,18,9,22,17,24,8,12,27]
foo2=[1,2,3]
map1=map(lambda x:x*2+10,foo)
def tt(x):
    return x*2+10
map2=map(tt,foo)

 PS:在Python中,function也是對象,所以可以不寫(),如果寫()爲方法或函數的調用

   2>filter(function or None, iterable) 

單個元素中,過濾出滿足條件的元素

f=filter(lambda x:x>10,foo)
print(f)
for i in f:
    print(i,end=" ")

   3>reduce()

將序列裏所有元素進行統計後,返回一個結果

#Python3中需要導入reduce
from functools import reduce
def re(x,y):
    return x+y
r=reduce(lambda a,b:a*b,foo)
# r=reduce(re,foo)
print("r={0}".format(r))
PS:由於reduce()是兩個元素執行操作,所以參數裏的方法需要兩個參數

3.sorted()

sorted(iterable, /, *, key=None, reverse=False)
    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可以提供自定義key函數以自定義排序順序。
    reverse flag can be set to request the result in descending order.可以設置反向標誌以按降序返回結果。

L = [('d',2),('a',4),('b',3),('c',2)]

#倒序先按數字排序,後按字母,
print(sorted(L,key=lambda x:(x[1],x[0]),reverse=True))

#將[0,1]中的0索引和1索引顛倒
a=lambda x:(x[1],x[0])
print(a([0,1]))


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章