Python built-in functions and serialization

Source: Internet
Author: User
Tags eval md5 md5 encryption serialization

Modifying the character Set global modification

Click Window

For a particular project

Right-click to have an attribute propertes

To a file, that is, the front Plus

is also right-click property, and this is not the point.
#模块的和模块的常用方法

    • The crucial __init__.py
      If you want to import into a module, be sure to have this file
    • Whether to master file __name
      If
      name = = ' \main__ '
      Return module file path + file name if not master file
    • Current file: __doc__
      Returns a comment at the module level, a function-level comment, which is a 6 quotation mark below the function, with a comment in the middle
    • __FILE__: Output current path function programming
    • Parametric def fun (Arg,*args,**kergs)
    • Default parameter Print arg
    • Variable-parameter print *args print **kergs
      One is a list, one is a dictionary
    • Returns the value return ' success '
      #!/usr/bin/env python#coding:utf-8def login(username):if username == "alex":    print "登录成功"else:    print "登录失败"if __name__ == "__main__":user = raw_input(‘username:‘)login(user)
      Yield
print range(10)for item in xrange(10):    print item    #输出的时候并没有全部创建,他只是一个生成器,说明他没有写入内存中    #也就是说每一次创建就只创建一个整数def foo():    yield 1re = foo()print re输出:[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]0123456789<generator object foo at 0x00000000030B8480>
def fool():    yield 1    yield 2    yield 3yield 4  #他的执行过程是,第一从从yield 1 执行,下一次直接从yield2开始执行 re = fool()print re#生成了一个生成器,每次遍历只生成一条for item in re :print item结果:<generator object fool at 0x0000000003248480>1234
def ReadLines():    seek = 0    while True:        with open(‘E:/temp.txt‘,‘r‘) as f :            f.seek(seek)            date = f.readline()            if date:                seek = f.tell()                yield date            else:                return print ReadLines()for item in ReadLines():    print item    
Ternary operations and lambda expressions ternary operations
  • code example:
    result = ' GT ' If 1>3 else ' it '
    Print result
  • Lambda expression ()
    code example:
    A = Lambda x,y:x+y
    Print a (.)
  • Map function ()
    Map (Lambda X:x*2,range (10))
    It means assigning each value of range to the front built-in function
  • Dir () lists the variables or method names built into the current file, listing only key
  • VARs () and Dir () are not the same as listing key and value
  • Type () to see the types of variables you have created
    A = [], essentially invoking a class to generate a list, essentially creating an instance of a class, like a tuple is the name of a class
  • From File Import Demo
  • Reload (Demo)
    Re-Import
  • ID ()
    View the data for a variable
  • CMP () function
    The CMP (x, y) function is used to compare 2 objects if x< y returns-1 if X==y returns 0 if X>y returns 1.
  • ABS () take absolute value
  • BOOL () Converts the result to a Boolean value
  • Divmod ()
    Calculates the result, returning the quotient and the remainder of a tuple
  • Max ([]) maximum value
  • Min ([]) minimum value
  • SUM ([]) sum
  • POW () exponential operation
  • Len () calculates the length (if Chinese is the length of the byte)
  • All (objects that can be iterated) can iterate over all the objects are true, then return ture, otherwise false
  • Any (object that can be iterated) has a true return ture
  • Chr (65) View characters
  • Ord (' a ') view Ascall value
  • Hex () 16 binary
  • Bin () 10 binary
  • Oct () 8 Binary
  • Range ()
  • Xrange ()
  • Enumerate (
    for k,v in enumerate([1,2,3,4]):print k,v输出:0 11 22 33 4
    #为程序增加一个序号li = [‘手表‘,‘汽车‘,‘房‘]for item in enumerate(li,1):print item[0],item[1]#1为初始值1 手表2 汽车3 房
  • Apply Execute function and function call
    Def say ():
    print ' Say in '
    Apply (say)
    output; say in
  • Map function () #遍历后面每一个序列的函数
    Map (Lambda X:x*2,range (10))
    It means assigning each value of range to the front (which can be a function)
    lala = [];def foo(arg):return arg + 100li = [11,22,33]lala = map(foo,li)print lala结果:[111, 122, 133]#也可以使用 lala.append(item+100)temp = map (lambda arg:arg+100,li)
  • The filter function #条件为真, adding it to the sequence
    temp = []li = [11,22,33]def foo(arg):if arg <22:    return Trueelse:    return Falsetemp = filter(foo,li)print temp将li序列中满足条件的返回temp序列中结果:11
  • Reduce accumulation (only two parameters)
    print reduce(lambda x,y:x+y,[1,2,3] )结果 6将前一次的计算结果,传递为第二次计算的第一个参数
  • Zip function #将列表中的第一个组成新的列表
    x = [[+]
    y = [4,5,6]
    z = [4,5,6]
    Print zip (x, y, z)
    Results:
    [(1, 4, 4), (2, 5, 5), (3, 6, 6)]
  • The Eval function #直接计算字符串类型的运算
    a =‘8*8‘print eval(a)结果:64
    Formatting of strings

    s = ' I am {0},{1} '
    Print S.format (' Alex ', ' xxx ')
    I am alex,xxx

    Reflection imports the module as a string and executes the function as a string (dynamically switches the database connection)

    Import of import OS is not allowed and is imported using temp method

    temp = ‘os‘model = __import__(temp)print modelprint model.path输出:<module ‘os‘ from ‘D:\pycharm\lib\os.pyc‘><module ‘ntpath‘ from ‘D:\pycharm\lib\ntpath.pyc‘>


    GetAttr is to find the Count function in the Mysqlhelper module
    function equals the count of the call.
    corresponding delattr () and hasattr () determine if the corresponding module is included in the function.

#使用random生成验证码
It uses the value of the Ascall to generate the

import randomprint random.random()print random.randint(1,5)#生成1-5之间的随机整数print random.randrange(1,3)#生成大于等于1,小于3的随机数
import randomcode = []for i in range(6):    if i == random.randint(1,5):        code.append(str(random.randint(1,5)))    else:        temp = random.randint(65,90)        code.append(chr(temp))print ‘‘.join(code)

#注意: The difference between join and + =
Join is more efficient, + = each time in memory to request a piece of space, join only request once

MD5 encryption
#!/usr/bin/env python#coding:utf-8import hashlibhash=hashlib.md5()hash.update(‘admin‘)print hash.hexdigest()print hash.digest()21232f297a57a5a743894a0e4a801fc3!#/)zW??C?JJ???#md5不能反解
Serialization and JSON

Application Example: (transfer files between Python and Python, single game Save in real time)

Why serialize?

A program will list the existence of one program, while another program uses this file. Using serialization after the other program to read, so that the two Python program between the memory of the exchange between the data, two separate processes in memory, their memory space can not access each other, if the two programs are not just simple list sharing, but also want other data exchange, the data may be more complex. And the hard disk can only save string type of data, can only be serialized, stored in the file, another program then read the contents of the file, and then deserialize it after the load into memory
Serialization: An object or (a list, a dictionary) that serializes an object through a Python-specific mechanism, which encrypts the object in a special form in a binary way, and can be deserialized after serialization.

Serialization of
import pickleli = [‘axex‘,11,22,‘ok‘,‘sb‘]print pickle.dumps(li)print type(pickle.dumps(li))输出结果:(lp0S‘axex‘p1aI11aI22aS‘ok‘p2aS‘sb‘p3a.<type ‘str‘>#是一个没有规则的字符串类型
Deserialization
import pickleli = [‘axex‘,11,22,‘ok‘,‘sb‘]dumpsed = pickle.dumps(li)print type(dumpsed)loadsed = pickle.loads(dumpsed)print loadsedprint type(loadsed)<type ‘str‘>[‘axex‘, 11, 22, ‘ok‘, ‘sb‘]<type ‘list‘>

Serializing a list to a file

import pickleli = [‘axex‘,11,22,‘ok‘,‘sb‘]pickle.dump(li,open(‘E:/temp.pk‘,‘w‘))result = pickle.load(open(‘E:/temp.pk‘,‘r‘))#将文件中反序列化

JSON: A standardized data format that JSON data in different formats.
# #两种序列化的区别

    • Pickle can only be used in Python
    • JSON is an interface supported by all languages
    • Pickle not only can dump regular data types, such as dictionaries, lists, collections, but also serialize classes, objects, and basically all types can be serialized, and JSON can only serialize regular data types. Because, in different languages, the format of the class is different.
    • Pickle serialized sequence of data is unreadable, but the JSON data format is used by the employing eye to see his format
      import jsonname_dic = {‘name‘:‘wupeiqi‘,‘age‘:23}print json.dumps(name_dic)输出结果:全部变成字符串{"age": 23, "name": "wupeiqi"}


      Why multiple u, because in the memory of using Unicode, you have the ability to utf-8, and then deserialization and then become Unicode

Python built-in functions and serialization

Related Article

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.