Python-functional programming, reflection, Random,md5,pickle,json,re,time

Source: Internet
Author: User

Advantages of functional Programming:

scalability, reusability (no Modification of previous code), readability (beginner easy to Understand)


__init__: used as a Python package file, otherwise it's just a folder

__name__: __name__== ' __main__ ' when called internally; __name__== file name when externally invoked

__file__: Current file path


1, The default parameters use

>>> 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. variable parameter *arg wrapper as list incoming function

>>> def show (*arg):
... for item in Arg:
.... print item
...
>>> show (' cxiong ', ' Xmzhang ')
Cxiong
Xmzhang
>>>


3. variable parameter **kargs wrapper for dictionary incoming function

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


When transferring a dictionary, you need to use the **kargs variable;

>>> user_dict={' cxiong ': $, ' Xmzhang ': 29}
>>> person (**user_dict)
(' Cxiong ', 29)
(' Xmzhang ', 29)
>>> person (user_dict)
Traceback (most recent):
File "<stdin>", line 1, in <module>
Typeerror:person () takes exactly 0 arguments (1 given)
>>>


4. Yield Usage

The object is created when the xrange iteration is called, and the object is created lazily;

>>> 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=f.readline ()
... if Data:
... Seek=f.tell ()
... yield data
.. else:
.. return
...
>>> for item in Alexreadlines ():
.... print item
...

>>> Print Alexreadlines ()
<generator Object Alexreadlines at 0x02a32cd8>



With open does not need to actively close the file stream

>>> F=open (' c:/cc/abc.html ')
>>> F.read ()
' >>> F.close ()
>>>


>>> with open (' c:/cc/abc.html ') as F:
... f.read ()
...
' >>>



def login (username):

If username== ' Alex ':

Return ' landing success '

Else

Return ' Login failed '

Yield can realize that the function execution process is not completed without waiting for the result of the function execution, that is, not blocking; when the project needs to call the function, call the next () method directly;

5. Lambda function

result= ' GT ' if 1>3 Else ' lt '

Equivalent to

Tmp=none

If 1>3:

tmp= ' GT '

Else

tmp= ' LT '

An anonymous function can only be called once;

Tmp=lambda X,y:x+y

Equivalent

def sum (x, y)

Return X+y


Http://www.cnblogs.com/wupeiqi/articles/4276448.html


6. Built-in Functions

>>> 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 it into an index sequence that can be used to get both the index and the value

>>> l1=[' Money ', ' house ', ' woman ']
>>> 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 Money
1 houses
2 women
>>>


Placeholder {},format Replace placeholder

>>> s= ' I am {0},{1} '
>>> s.format (' Cxiong ', 29)
' I am cxiong,29 '


String as an expression operation

>>> a= ' 8+8 '
>>> Eval (a)
16
>>> b= ' 4*2 '
>>> Eval (b)
8




7. Reflection

__import__: importing modules as strings

>>> 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: executing functions in the form of strings

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. Common Module 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
>>>


Scenario: Generate a verification code

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, Common Module HASHLIB:MD5 encryption

>>> Import Hashlib
>>> hash=hashlib.md5 () #md5对象
>>> hash.update (' Admin ')
>>> hash.hexdigest ()
' 21232F297A57A5A743894A0E4A801FC3 '
>>> hash.hexdigest ()


10. Common Modules: Serialized-pickle

Serialization: the binary format formats the Python object as a string;

Deserialization: You can convert an encrypted string to an existing object

Purpose and function: can only be used in python, data storage, all Python objects (classes, functions, dictionaries, lists, etc.) are serialized into files for saving;

Python and Python program to interact with the memory space data, because the hard disk can only hold strings, unable to hold data objects;

>>> 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 ', one, one, ' OK ', ' Xmzhang ']

In [+]: pickle.dump (l1,open ('/tmp/1.txt ', ' W '))


In [+]: exit
[email protected] ~]$ Cat/tmp/1.txt
(lp0
S ' Cxiong '
P1
AI11
AI22
As ' OK '
P2
As ' Xmzhang '
P3
A.

[email protected] ~]$


In [2]: pickle.load (open ('/tmp/1.txt ', ' r '))
Out[2]: [' cxiong ', one, a, ' OK ', ' Xmzhang ']


11. Common Modules: Serialized-json

Json: data formats supported by all languages; JSON can only serialize regular objects (dictionaries, lists); after JSON serialization, the string format is visible

The difference between JSON and pickle

In [5]: name_dict={' name ': ' Cxiong ', ' age ': 29}

In [6]: json.dumps (name_dict)
Out[6]: ' {' age ': "name": "cxiong"} '


In [7]: pickle.dumps (name_dict)
Out[7]: "(dp0\ns ' age ' \np1\ni29\nss ' name ' \np2\ns ' Cxiong ' \np3\ns."



12. Common Module RE

Character:

\d: Digital

\w: Letters

\ t: Blank

Number:

*:

+

? :

{m}:

{m,n}:


Match from scratch; search Global match; match only first

In []: r1=re.match (' \d+ ', ' asdfasd123asdfwe32 ')

In [+]: r2=re.search (' \d+ ', ' asdfasd123asdfwe32 ')

In []: R1

In [+]: R2
Out[21]: <_sre. Sre_match at 0x2e28370>

In []: R1.group ()
---------------------------------------------------------------------------
Attributeerror Traceback (most Recent)
<ipython-input-22-d8a389c401ef> in <module> ()
----> 1 R1.group ()

Attributeerror: ' Nonetype ' object has no attribute ' group '

In [all]: R2.grou
R2.group r2.groupdict r2.groups

In [all]: R2.group ()
Out[23]: ' 123 '


FindAll Match all modes

In []: r3=re.findall (' \d+ ', ' asdfasd123asdfwe32 ')

In [+]: R3
Out[25]: [' 123 ', ' 32 ']


Compile compilation mode

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 () get matching group contents

In [6]: r2=re.search (' (\d+) asdf (\d+) ', ' 1234asdf2345 ')

In [7]: R2.group ()
Out[7]: ' 1234asdf2345 '

In [8]: r2.groups ()
Out[8]: (' 1234 ', ' 2345 ')


Information:

Https://deerchao.net/tutorials/regex/regex-1.htm


13. Common Modules: Time

Three forms of Expression:

Timestamp: seconds after January 1, 1970

Tuples include: year, day, week, etc... time.struct_time

Formatted string 2014-11-1111:11print time.time ()


In [9]: import time

In [ten]: time.time ()
Out[10]: 1494069737.874593


In [all]: 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 []: time.strftime ('%y-%m-%d%h:%m:%s ')
Out[14]: ' 2017-05-06 04:28:22 '


string format---> tuple format

In [+]: 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)


Tuple format---> timestamp format

In [+]: 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 []: time.mktime (time.localtime ())
Out[18]: 1494070270.0





Python-functional programming, reflection, Random,md5,pickle,json,re,time

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.