python学习手册中的一些易忘的点(第4部分)

1.python函数高聚合低耦合
1)对于输入使用参数并且对于输出使用return
2)只有在真正必要的情况下使用全局变量
3)不要改变可变类型的参数,除非调用者希望这样做
4)每个函数都应该有一个单一的、统一的目标
5)每一个函数应该相对较小
6)避免直接改变在另一个文件中的变量

2.递归处理任意结构
>>> a=[3,[2,[2,3,4],2],1,[1,5,[1,3,3]]]
>>> def sumtree(L):
...   tot=0
...   for x in L:
...     if not isinstance(x,list):
...       tot+=x
...     else:
...       tot+=sumtree(x)
...   return tot
...
>>> sumtree(a)
30
>>>

3.lamdba,map,filter,reduce用法
>>> map((lambda x: x+3),[1,2,3,4,5,6])
[4, 5, 6, 7, 8, 9]
>>> map((lambda x,y: x+y),[1,2,3,4,5,6],[2,3,4,5,6,7])
[3, 5, 7, 9, 11, 13]
>>>
>>> filter((lambda x: x%2==0),[1,2,3,4,5,6])
[2, 4, 6]
>>> reduce((lambda x,y: x+y),[1,2,3,4,5,6])
21
>>> reduce((lambda x,y: x*y),[1,2,3,4,5,6])
720
>>>

4.任意参数
1)收集参数
>>> def f1(*args):
...   print type(args)
...   print args
...
>>> f1(1,2,3,4)
<type 'tuple'>
(1, 2, 3, 4)
>>> def f1(**args):
...   print type(args)
...   print args
...
>>> f1(a=1,b=2)
<type 'dict'>
{'a': 1, 'b': 2}
>>>
2)解包参数
>>> def f(a,b,c,d):
...   print a,b,c,d
...
>>> f(*(1,2,3,4))
1 2 3 4
>>>
————————————————
>>> def f(a,b,c,d):print a,b,c,d
...
>>> f('1',*(1,2,3))
1 1 2 3
>>> f('1',b=2,**{'c':1,'d':2})
1 2 1 2
————————————————
>>> def f(a,*args,**dics):print a,args,dics
...
>>> f('1',*('a','b','c'),b=2,**{'1':1,'2':2})
1 ('a', 'b', 'c') {'1': 1, '2': 2, 'b': 2}
>>>


5.迭代/解析
双层迭代
for i in map(iter,('12345','abcde')):print list(i)
...
['1', '2', '3', '4', '5']
['a', 'b', 'c', 'd', 'e']
>>>
————————————————
字典、集合解析
>>> {x:x**2 for x in range(10)}
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81}
>>> {x**2 for x in range(10)}
set([0, 1, 4, 81, 64, 9, 16, 49, 25, 36])
>>>
>>> [x for x in range(10) if x%2==0]
[0, 2, 4, 6, 8]
>>> {x:y for x in range(5) if x%2==0 for y in range(5) if y%2==1}
{0: 3, 2: 3, 4: 3}
>>>
————————————————
函数生成器(构造可迭代)
>>> def gensquares(N):
...   for i in range(N):
...     yield i**2
...
>>> for i in gensquares(5):print i
...
0
1
4
9
16
>>> d=gensquares(5)
>>> type(d)
<type 'generator'>
>>> [i for i in d]
[0, 1, 4, 9, 16]
>>>
>>> d=gensquares(6)
>>> next(d)
0
>>> next(d)
1
>>>
————————————————
嵌套迭代
>>> def myzip(*args):
...   iters=map(iter,args)
...   while iters:
...     res = [next(i) for i in iters]
...     yield tuple(res)
...
>>> myzip('1234')
<generator object myzip at 0x7fe17db37c30>
>>> list(myzip('1234'))
[('1',), ('2',), ('3',), ('4',)]
>>> myzip('12345','abcde')
<generator object myzip at 0x7fe17db37c30>
>>> list(myzip('12345','abcde'))
[('1', 'a'), ('2', 'b'), ('3', 'c'), ('4', 'd'), ('5', 'e')]
>>>
————————————————
>>> g=((x,x*x,x**3) for x in range(10))
>>> next(g)
(0, 0, 0)
>>> next(g)
(1, 1, 1)
>>> next(g)
(2, 4, 8)

posted on 2018-08-21 12:43  米仓山下  阅读(190)  评论(0编辑  收藏  举报

导航