用小例子来记住你们吧。
lambda
In[3]: g = lambda x: x**2
In[4]: g(4)
Out[4]: 16
rjust/ljust
TypeError Traceback (most recent call last)
/home/natsuki/<ipython-input-12-b9afd2d8d4c0> in <module>()
----> 1 'abad'.rjust(5,'abd')
TypeError: must be char, not str
filter/map/reduce
In[13]: foo = [2, 18, 9, 22, 17, 24, 8, 12, 27]
In[14]: print filter(lambda x: x % 3 == 0, foo)
[18, 9, 24, 12, 27]
In[18]: print [x for x in foo if x % 3 == 0]
[18, 9, 24, 12, 27]
In[15]: print map(lambda x: x * 2 + 1, foo)
[5, 37, 19, 45, 35, 49, 17, 25, 55]
In[17]: print [x * 2 + 1 for x in foo]
[5, 37, 19, 45, 35, 49, 17, 25, 55]
In[16]: print reduce(lambda x, y: x + y, foo)
139
In[20]: def reduce(bin_func, seq, init = None):
....: lseq = list(seq)
....: if init is None:
....: res = lseq.pop(0)
....: else:
....: res = init
....: for each in lseq:
....: res = bin_func(res, each)
....: return res
....: print reduce(lambda x, y: x + y,foo)
....: #再按一次Enter
139
#这个可以学习,学习
In[24]: def buildConnectionString(params):
....: return ";".join(["%s=%s" % (k, v) for k, v in params.items()]) ....:
In[25]: myParams = {"server":"mpilgrim", \
....: "database":"master", \
....: "uid":"sa", \
....: "pwd":"secret" \
....: }
In[26]: print buildConnectionString(myParams)
pwd=secret;database=master;uid=sa;server=mpilgrim