首页 > 代码库 > python-函数式编程,反射,random,md5,pickle,json,re,time
python-函数式编程,反射,random,md5,pickle,json,re,time
函数式编程的优点:
可扩展性、可复用性(不修改以前代码)、可阅读性(初学者通俗易懂)
__init__:作为python包文件使用,否则只是个文件夹
__name__:文件内部调用时__name__==‘ __main__‘;外部调用时,__name__==文件名
__file__:当前文件路径
1、默认参数使用
>>> def person(name,action=‘eat...‘,where=‘beijing‘):
... print name,action,‘in ‘+where
...
>>> person(‘cxiong‘)
cxiong eat... in beijing
>>> person(‘xmzhang‘,‘sleep‘)
xmzhang sleep in beijing
>>> person(‘cxiong‘,where=‘shanghai‘,action=‘work‘)
cxiong work in shanghai
>>> person(‘cxiong‘,‘work‘,‘wuhan‘)
cxiong work in wuhan
2、可变参数*arg包装为列表传入函数
>>> def show(*arg):
... for item in arg:
... print item
...
>>> show(‘cxiong‘,‘xmzhang‘)
cxiong
xmzhang
>>>
3、可变参数**kargs包装为字典传入函数
>>> def person(**kargs):
... for item in kargs.items():
... print item
...
>>> person(name=‘cxiong‘,age=29)
(‘age‘, 29)
(‘name‘, ‘cxiong‘)
>>> person(name=‘xmzhang‘,age=29)
(‘age‘, 29)
(‘name‘, ‘xmzhang‘)
将字典传输时,需要使用**kargs变量;
>>> user_dict={‘cxiong‘:29,‘xmzhang‘:29}
>>> person(**user_dict)
(‘cxiong‘, 29)
(‘xmzhang‘, 29)
>>> person(user_dict)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: person() takes exactly 0 arguments (1 given)
>>>
4、yield用法
xrange迭代调用时才创建对象,延时创建对象;
>>> for i in xrange(10):
... print i
...
0
1
2
3
4
5
6
7
8
9
>>>
>>> def y():
... yield 1
...
>>> y1=y()
>>> print y1
<generator object y at 0x0293C288>
>>> for item in y1:
... print item
...
1
>>> def y():
... yield 1
... yield 2
... yield 3
... yield 4
... yield 5
...
>>> y2=y()
>>> print y2
<generator object y at 0x02A31670>
>>> for item in y2:
... print item
...
1
2
3
4
5
>>>
>>> def AlexReadlines():
... seek=0
... while True:
... with open(‘c:/cc/abc.html‘,‘r‘) as f:
... f.seek(seek)
... data=http://www.mamicode.com/f.readline()
... if data:
... seek=f.tell()
... yield data
... else:
... return
...
>>> for item in AlexReadlines():
... print item
...
<h1>hello cccccccccc</h1>
>>> print AlexReadlines()
<generator object AlexReadlines at 0x02A32CD8>
with open不需要主动关闭文件流
>>> f=open(‘c:/cc/abc.html‘)
>>> f.read()
‘<h1>hello cccccccccc</h1>‘
>>> f.close()
>>>
>>> with open(‘c:/cc/abc.html‘) as f:
... f.read()
...
‘<h1>hello cccccccccc</h1>‘
>>>
def login(username):
if username==’alex’:
return ‘登陆成功’
else:
return ‘登陆失败’
yield可以实现函数执行过程未完成时不用等待函数的执行结果,即不阻塞;当工程需要调用函数时,直接调用next()方法即可;后面再细讲
5、lambda函数
result= ‘gt’ if 1>3 else ‘lt’
等价于
tmp=None
if 1>3:
tmp=’gt’
else:
tmp=’lt’
匿名函数只能调用一次;
tmp=lambda x,y:x+y
相当于
def sum(x,y)
return x+y
http://www.cnblogs.com/wupeiqi/articles/4276448.html
6、内置函数
>>> map(lambda x:x+1,[1,2,3]) #all序列
[2, 3, 4]
>>> filter(lambda x:x==1,[1,23,44]) #True序列
[1]
>>> reduce(lambda x,y:x+y,[1,2,3]) #累加
6
>>>
enumerate将其组成一个索引序列,利用它可以同时获得索引和值
>>> l1=[‘钱‘,‘房子‘,‘女人‘]
>>> for item in enumerate(l1):
... print item
...
(0, ‘\xc7\xae‘)
(1, ‘\xb7\xbf\xd7\xd3‘)
(2, ‘\xc5\xae\xc8\xcb‘)
>>> for item in enumerate(l1):
... print item[0],item[1]
...
0 钱
1 房子
2 女人
>>>
占位符{},format替换占位符
>>> s=‘i am {0},{1}‘
>>> s.format(‘cxiong‘,29)
‘i am cxiong,29‘
字符串作为表达式运算
>>> a=‘8+8‘
>>> eval(a)
16
>>> b=‘4*2‘
>>> eval(b)
8
7、反射
__import__:字符串的形式导入模块
>>> tmp=‘sys‘
>>> model=__import__(tmp)
>>> model.path
[‘‘, ‘C:\\Python27\\lib\\site-packages\\pip-8.0.3-py2.7.egg‘, ‘C:\\Python27\\lib\\site-packages\\paramiko-1.16.0-py2.7.egg‘, ‘C:\\WINDOWS\\SYSTEM32\\python27.zip‘, ‘C:\\Python27\\DLLs‘, ‘C:\\Python27\\lib‘, ‘C:\\Python27\\lib\\plat-win‘, ‘C:\\Python27\\lib\\lib-tk‘, ‘C:\\Python27‘, ‘C:\\Python27\\lib\\site-packages‘]
>>>
getattr:字符串的形式执行函数
mysql,sqlserver
>>> f=getattr(model,‘path‘)
>>> f
[‘‘, ‘C:\\Python27\\lib\\site-packages\\pip-8.0.3-py2.7.egg‘, ‘C:\\Python27\\lib\\site-packages\\paramiko-1.16.0-py2.7.egg‘, ‘C:\\WINDOWS\\SYSTEM32\\python27.zip‘, ‘C:\\Python27\\DLLs‘, ‘C:\\Python27\\lib‘, ‘C:\\Python27\\lib\\plat-win‘, ‘C:\\Python27\\lib\\lib-tk‘, ‘C:\\Python27‘, ‘C:\\Python27\\lib\\site-packages‘]
>>>
8、常用模块random
>>> import random
>>> random.random()
0.20107276223352322
>>> random.random()
0.08696208484961188
>>> random.random()
0.2274291961816528
>>> random.randint(1,5)
5
>>> random.randint(1,5)
1
>>> random.randint(1,5)
1
>>> random.randint(1,5)
4
>>> random.randint(1,5)
3
>>>
应用场景:生成验证码
code=[]
>>> for i in range(4):
... if i ==random.randint(1,4):
... print random.randint(1,4)
... else:
... tmp=random.randint(65,90)
... print chr(tmp)
9、常用模块hashlib:md5加密
>>> import hashlib
>>> hash=hashlib.md5() #md5对象
>>> hash.update(‘admin‘)
>>> hash.hexdigest()
‘21232f297a57a5a743894a0e4a801fc3‘
>>> hash.hexdigest()
10、常用模块:序列化-pickle
序列化:二进制格式将Python对象进行格式化为字符串形式;
反序列化:可以将加密的字符串转化为原有对象
用途及作用:只能在python中使用;数据存储,将python所有的对象(类、函数、字典、列表等)序列化为文件进行保存;
python与python程序之间内存空间数据交互;因为硬盘中只能存放字符串,无法存放数据对象;
>>> import pickle
>>> l1=[‘cxiong‘,11,22,‘ok‘,‘xmzhang‘]
>>> pickle.dumps(l1)
"(lp0\nS‘cxiong‘\np1\naI11\naI22\naS‘ok‘\np2\naS‘xmzhang‘\np3\na."
>>> s1=pickle.dumps(l1)
>>> s1
"(lp0\nS‘cxiong‘\np1\naI11\naI22\naS‘ok‘\np2\naS‘xmzhang‘\np3\na."
>>> type(s1)
<type ‘str‘>
>>> l1=pickle.loads(s1)
>>> l1
[‘cxiong‘, 11, 22, ‘ok‘, ‘xmzhang‘]
In [17]: pickle.dump(l1,open(‘/tmp/1.txt‘,‘w‘))
In [18]: exit
[cxiong@localhost ~]$ cat /tmp/1.txt
(lp0
S‘cxiong‘
p1
aI11
aI22
aS‘ok‘
p2
aS‘xmzhang‘
p3
a.
[cxiong@localhost ~]$
In [2]: pickle.load(open(‘/tmp/1.txt‘,‘r‘))
Out[2]: [‘cxiong‘, 11, 22, ‘ok‘, ‘xmzhang‘]
11、常用模块:序列化-json
json:所有语言都支持的数据格式;json只能序列化常规的对象(字典、列表);json序列化后,字符串格式可见
json与pickle的区别
In [5]: name_dict={‘name‘:‘cxiong‘,‘age‘:29}
In [6]: json.dumps(name_dict)
Out[6]: ‘{"age": 29, "name": "cxiong"}‘
In [7]: pickle.dumps(name_dict)
Out[7]: "(dp0\nS‘age‘\np1\nI29\nsS‘name‘\np2\nS‘cxiong‘\np3\ns."
12、常用模块re
字符:
\d:数字
\w:字母
\t:空白
次数:
*:
+:
?:
{m}:
{m,n}:
match从头开始匹配;search全局匹配;只匹配第一个
In [18]: r1=re.match(‘\d+‘,‘asdfasd123asdfwe32‘)
In [19]: r2=re.search(‘\d+‘,‘asdfasd123asdfwe32‘)
In [20]: r1
In [21]: r2
Out[21]: <_sre.SRE_Match at 0x2e28370>
In [22]: r1.group()
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-22-d8a389c401ef> in <module>()
----> 1 r1.group()
AttributeError: ‘NoneType‘ object has no attribute ‘group‘
In [23]: r2.grou
r2.group r2.groupdict r2.groups
In [23]: r2.group()
Out[23]: ‘123‘
findall匹配所有模式
In [24]: r3=re.findall(‘\d+‘,‘asdfasd123asdfwe32‘)
In [25]: r3
Out[25]: [‘123‘, ‘32‘]
compile编译模式
In [1]: import re
In [3]: com=re.compile(‘\d+‘)
In [4]: type(com)
Out[4]: _sre.SRE_Pattern
In [5]: com.findall(‘asdf123aadsf3454aafadsf523‘)
Out[5]: [‘123‘, ‘3454‘, ‘523‘]
groups()获取匹配组内容
In [6]: r2=re.search(‘(\d+)asdf(\d+)‘,‘1234asdf2345‘)
In [7]: r2.group()
Out[7]: ‘1234asdf2345‘
In [8]: r2.groups()
Out[8]: (‘1234‘, ‘2345‘)
资料:
https://deerchao.net/tutorials/regex/regex-1.htm
13、常用模块:time
三种表现形式:
时间戳:1970年1月1日之后的秒
元组 包含了:年、日、星期等...time.struct_time
格式化的字符串 2014-11-1111:11print time.time()
In [9]: import time
In [10]: time.time()
Out[10]: 1494069737.874593
In [11]: time.gmtime()
Out[11]: time.struct_time(tm_year=2017, tm_mon=5, tm_mday=6, tm_hour=11, tm_min=26, tm_sec=8, tm_wday=5, tm_yday=126, tm_isdst=0)
In [14]: time.strftime(‘%Y-%m-%d %H:%M:%S‘)
Out[14]: ‘2017-05-06 04:28:22‘
字符串格式--->元组格式
In [16]: time.strptime(‘2017-05-06‘,‘%Y-%m-%d‘)
Out[16]: time.struct_time(tm_year=2017, tm_mon=5, tm_mday=6, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=5, tm_yday=126, tm_isdst=-1)
元组格式--->时间戳格式
In [17]: time.localtime()
Out[17]: time.struct_time(tm_year=2017, tm_mon=5, tm_mday=6, tm_hour=4, tm_min=30, tm_sec=56, tm_wday=5, tm_yday=126, tm_isdst=1)
In [18]: time.mktime(time.localtime())
Out[18]: 1494070270.0
python-函数式编程,反射,random,md5,pickle,json,re,time