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')]