python函數(shù)總結(jié)

1预明、線性迭代可以直接用for循環(huán)状知,效率高并且節(jié)省空間贸铜,對于任意深度的任意嵌套一般用遞歸實現(xiàn)

例:計算一個嵌套子列表中所有數(shù)字之和堡纬。

def sum_list(L):
    if not L:
        return 0
    if type(L[0]) == list:
        return sum_list(L[0])+sum_list(L[1:])
    else:
        return L[0]+sum_list(L[1:])
#或
def sum_list2(L):
    total = 0
    for x in L:
        if not isinstance(x,list):
            total+=x
        else:
            total+=sum_list2(x)
    return total

print(sum_list2(L))
print(sum_list2([]))
print(sum_list2([1,[2,[3,[4,[5]]]]]))
print(sum_list2([[[[[1],2],3],4],5]))

結(jié)果:
55
0
15
15

函數(shù)也可以當(dāng)成參數(shù)傳遞,將上面兩個函數(shù)封裝成一個函數(shù)調(diào)用:

def sum(func,arg):
    return func(arg)
print(sum(sum_list,L))
print(sum(sum_list2,L))
結(jié)果:
55
55

2萨脑、函數(shù)頭部的*args隐轩、**kwargs與函數(shù)調(diào)用時的*args、**kwargs區(qū)別

函數(shù)頭部的args表示將位置參數(shù)的收集到一個元組中渤早,kwargs表示將關(guān)鍵字參數(shù)收集到一個字典中
函數(shù)調(diào)用時的
args表示對args進行解包成位置參數(shù)傳給函數(shù)职车,**kwargs會以鍵值對的形式解包一個字典,最終以key=value形式的參數(shù)傳給函數(shù)鹊杖。

3悴灵、函數(shù)自省

a = 'aaa'
def func_test(func, arg):
    print(arg)
    b = 'hello'
    global a
    def x():
        c = 'ccc'
        return c
    return func(arg)
print(func_test.__name__)#獲得函數(shù)的名稱
print(dir(func_test))#獲得函數(shù)對象的所有屬性
print(func_test.__code__)#獲得函數(shù)的代碼對象
print(dir(func_test.__code__))#獲得函數(shù)代碼對象的所有屬性
print(func_test.__code__.co_varnames)#獲得函數(shù)的本地變量,包括參數(shù)和內(nèi)部定義的變量,不包括內(nèi)部引用的全局變量
print(func_test.__code__.co_argcount)#獲得函數(shù)參數(shù)的個數(shù)
# 函數(shù)是對象骂蓖,可以dir檢查它的屬性积瞒,函數(shù)的內(nèi)省工具附加了代碼對象(__code__),可以獲得函數(shù)的本地變量和參數(shù)等方面細節(jié)

結(jié)果:
func_test
['__annotations__', '__call__', '__class__', '__closure__', '__code__', '__defaults__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__get__', '__getattribute__', '__globals__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__kwdefaults__', '__le__', '__lt__', '__module__', '__name__', '__ne__', '__new__', '__qualname__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__']
<code object func_test at 0x0000029883582930, 登下。茫孔。>
['__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'co_argcount', 'co_cellvars', 'co_code', 'co_consts', 'co_filename', 'co_firstlineno', 'co_flags', 'co_freevars', 'co_kwonlyargcount', 'co_lnotab', 'co_name', 'co_names', 'co_nlocals', 'co_stacksize', 'co_varnames']
('func', 'arg', 'b', 'x')
2

4叮喳、 函數(shù)是對象,可以給函數(shù)添加屬性缰贝,可以認為是‘靜態(tài)本地變量’馍悟,它的值在函數(shù)退出后仍保留,屬性跟對象有關(guān)而不是跟作用域有關(guān)剩晴。

func_test.test = 'test-attribute'
print(dir(func_test))
結(jié)果:
['__annotations__', '__call__', '__class__', '__closure__', '__code__', '__defaults__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__get__', '__getattribute__', '__globals__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__kwdefaults__', '__le__', '__lt__', '__module__', '__name__', '__ne__', '__new__', '__qualname__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'test']

5锣咒、 函數(shù)注解

def func_test2(a:'spam'=4,b:(1,10)=5,c:float=6) -> int:
    return a+b+c
print(func_test2())
print(func_test2.__annotations__) 
結(jié)果:
15
{'a': 'spam', 'b': (1, 10), 'c': <class 'float'>, 'return': <class 'int'>}

a:'spam'=4表示用a的默認值是4,并用字符串spam注解它赞弥,函數(shù)結(jié)果的注解存儲在鍵‘return’下
注解的作用:注解可用作參數(shù)類型或值的特定限制

6毅整、 lambda 函數(shù)

def 定義的是語句;lambda定義的是表達式

li = [lambda x:x**2,lambda x:x**3,lambda x:x*9]
for l in li:
    print(l(5))

import sys
showall = lambda x:list(map(sys.stdout.write,x))
showall(['spam\n','hello\n','world\n'])

m = map(lambda x:x+10,[1,2,3,4])
print(m)
print(list(m))
結(jié)果:
25
125
45
spam
hello
world
<map object at 0x0000029883599DD8>
[11, 12, 13, 14]

7绽左、map函數(shù)

map函數(shù)期待一個N參數(shù)的函數(shù)作用于N序列
print(list(map(pow,[2,3,4],[4,5,6])))# => 24,35,4**6

可以通過for模擬map的功能悼嫉,但沒有必要,自帶的map的效率更高

print(list(filter((lambda x:x>0),range(-10,10))))

from functools import reduce
print((reduce((lambda x,y:x+y),[1,3,4],0)))

import operator
print(dir(operator))
結(jié)果:
[16, 243, 4096]
[1, 2, 3, 4, 5, 6, 7, 8, 9]
8
['abs', 'add', 'all', 'and', 'builtins', 'cached', 'concat', 'contains', 'delitem', 'doc', 'eq', 'file', 'floordiv', 'ge', 'getitem', 'gt', 'iadd', 'iand', 'iconcat', 'ifloordiv', 'ilshift', 'imatmul', 'imod', 'imul', 'index', 'inv', 'invert', 'ior', 'ipow', 'irshift', 'isub', 'itruediv', 'ixor', 'le', 'loader', 'lshift', 'lt', 'matmul', 'mod', 'mul', 'name', 'ne', 'neg', 'not', 'or', 'package', 'pos', 'pow', 'rshift', 'setitem', 'spec', 'sub', 'truediv', 'xor', 'abs', 'abs', 'add', 'and', 'attrgetter', 'concat', 'contains', 'countOf', 'delitem', 'eq', 'floordiv', 'ge', 'getitem', 'gt', 'iadd', 'iand', 'iconcat', 'ifloordiv', 'ilshift', 'imatmul', 'imod', 'imul', 'index', 'indexOf', 'inv', 'invert', 'ior', 'ipow', 'irshift', 'is_', 'is_not', 'isub', 'itemgetter', 'itruediv', 'ixor', 'le', 'length_hint', 'lshift', 'lt', 'matmul', 'methodcaller', 'mod', 'mul', 'ne', 'neg', 'not_', 'or_', 'pos', 'pow', 'rshift', 'setitem', 'sub', 'truediv', 'truth', 'xor']

8妇菱、 生成器

def ge(n):
    for i in range(n):
        x = yield i ** 2
        print(x)
    return 'end'

g = ge(5)
print(g)
print(dir(g))

print(next(g))
print(next(g))
print('send 34:',g.send(34))
# print('send 66:',g.send(66))
#
# print(next(g))
# print(next(g))
# print(next(g))
# print(next(g))
# print(next(g))

# for i in ge(5):
#     print('-'*30)
#     print(i)
結(jié)果:
<generator object ge at 0x0000029883566938>
['__class__', '__del__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__lt__', '__name__', '__ne__', '__new__', '__next__', '__qualname__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'close', 'gi_code', 'gi_frame', 'gi_running', 'gi_yieldfrom', 'send', 'throw']
0
None
1
34
send 34: 4

9承粤、 zip 和 map

z = zip([1,2,3],[4,5,6])
print(list(z))

m = map(pow,[1,2,3],[4,5,6])
print(list(m))

def mymap(func,*seqs):
    # res = []
    # for args in zip(*seqs):
    #     res.append(func(*args))
    # return res
    return [func(*args) for args in zip(*seqs)]

print(list(mymap(pow,[1,2,3],[4,5,6])))
print(list(mymap(abs,[1,2,-3])))

def mymap2(func,*seqs):
    return (func(*args) for args in zip(*seqs))

print(list(mymap2(pow,[1,2,3],[4,5,6])))
print(list(mymap2(abs,[1,2,-3])))

res = all([1,2,''])
res1 = any([1,2,''])
print(res,res1)

def myzip(*seqs):
    seqs = [list(S) for S in seqs]
    print(seqs)
    res = []
    while all(seqs):
        res.append(tuple(S.pop(0) for S in seqs))
    return res
s1,s2 = 'abc','xyz123'
print(myzip(s1,s2))
結(jié)果:
[(1, 4), (2, 5), (3, 6)]
[1, 32, 729]
[1, 32, 729]
[1, 2, 3]
[1, 32, 729]
[1, 2, 3]
False True
[['a', 'b', 'c'], ['x', 'y', 'z', '1', '2', '3']]
[('a', 'x'), ('b', 'y'), ('c', 'z')]
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市闯团,隨后出現(xiàn)的幾起案子辛臊,更是在濱河造成了極大的恐慌,老刑警劉巖房交,帶你破解...
    沈念sama閱讀 217,826評論 6 506
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件彻舰,死亡現(xiàn)場離奇詭異,居然都是意外死亡候味,警方通過查閱死者的電腦和手機刃唤,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,968評論 3 395
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來白群,“玉大人尚胞,你說我怎么就攤上這事≈穆” “怎么了笼裳?”我有些...
    開封第一講書人閱讀 164,234評論 0 354
  • 文/不壞的土叔 我叫張陵,是天一觀的道長粱玲。 經(jīng)常有香客問我躬柬,道長,這世上最難降的妖魔是什么抽减? 我笑而不...
    開封第一講書人閱讀 58,562評論 1 293
  • 正文 為了忘掉前任允青,我火速辦了婚禮,結(jié)果婚禮上卵沉,老公的妹妹穿的比我還像新娘颠锉。我一直安慰自己法牲,他們只是感情好,可當(dāng)我...
    茶點故事閱讀 67,611評論 6 392
  • 文/花漫 我一把揭開白布木柬。 她就那樣靜靜地躺著皆串,像睡著了一般。 火紅的嫁衣襯著肌膚如雪眉枕。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,482評論 1 302
  • 那天怜森,我揣著相機與錄音速挑,去河邊找鬼。 笑死副硅,一個胖子當(dāng)著我的面吹牛姥宝,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播恐疲,決...
    沈念sama閱讀 40,271評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼腊满,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了培己?” 一聲冷哼從身側(cè)響起碳蛋,我...
    開封第一講書人閱讀 39,166評論 0 276
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎省咨,沒想到半個月后肃弟,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,608評論 1 314
  • 正文 獨居荒郊野嶺守林人離奇死亡零蓉,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,814評論 3 336
  • 正文 我和宋清朗相戀三年笤受,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片敌蜂。...
    茶點故事閱讀 39,926評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡箩兽,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出章喉,到底是詐尸還是另有隱情汗贫,我是刑警寧澤,帶...
    沈念sama閱讀 35,644評論 5 346
  • 正文 年R本政府宣布囊陡,位于F島的核電站芳绩,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏撞反。R本人自食惡果不足惜妥色,卻給世界環(huán)境...
    茶點故事閱讀 41,249評論 3 329
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望遏片。 院中可真熱鬧嘹害,春花似錦撮竿、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,866評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至许师,卻和暖如春房蝉,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背微渠。 一陣腳步聲響...
    開封第一講書人閱讀 32,991評論 1 269
  • 我被黑心中介騙來泰國打工搭幻, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人逞盆。 一個月前我還...
    沈念sama閱讀 48,063評論 3 370
  • 正文 我出身青樓檀蹋,卻偏偏與公主長得像,于是被迫代替她去往敵國和親云芦。 傳聞我的和親對象是個殘疾皇子俯逾,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 44,871評論 2 354

推薦閱讀更多精彩內(nèi)容