Python Base Set

Source: Internet
Author: User
Tags shallow copy

1. Set

Set is an unordered , non-repeating collection

Li=[11,22,33,11]s=set (LI) print (s) {11,22,33}

Method provided by Set

1.add(self*args, **kwargs):   添加

Li={11,22,33}s=li.add () print (LI) {11,22,33,44}

2.clear(self*args, **kwargs):  清除内容

Li={11,22,33,44}s=li.clear () print (LI) str ()

3.difference(self*args, **kwargs):  寻找不同 s=A.different(B)  A中存在的B中不存在的元素赋值给s

Li={11,22,33,44,11}l2={22,44,55,11}s=li.difference (L2) print (s) {33}

difference_update( self 4 . * args,  * * kwargs): Find and update the original s=a in different ways. difference_update( b) A non-existent element in B that exists in a to find and update a

Li={11,22,33,44}l2={11,22,33,55}li.different_upper (L2) print (LI) {44}

5, discard( self * args,  * * kwargs): Remove the specified element does not exist no error

Li={11,22,33,44}s=li.discard (one) print (LI) {22,33,44}

intersection( self 6 . * args,  * * kwargs): 寻找相同 s=A.intersection(B)  A、B中都存在的元素赋值给s

Li={11,22,33,44}l2={11,22,44}s=li.intersection (L2) print (s) {11,22,44}

intersection_update( self 7 . * args,  * * kwargs):  把相同的找到并更新原有的  s=A.intersection_update(B)  AB中都存在的元素找到并更新A

Li={11,22,33,44}l2={11,22,44}s=li.intersection_update (L2) print (LI) {11,22,44}

isdisjoint( self 8 . * args,  * * kwargs): 查看俩个集合有没有交集 如果有则返回False 没有返回True

Li={11,22,33,44}l2={00,77}s=li.isdisjoint (L2) print (s) True

9, issubset( self * args,  * * kwargs): Whether it is a sub-sequence

Li={11,22,33,44}l2={00,77}s=li.issubset (L2) print (s) False

10, issuperset( self * args,  * * kwargs): Whether it is a parent sequence

Li={11,22,33,44}l2={00,77}s=li.issuperset (L2) print (s) False

11. pop( self * args,  * * kwargs): Randomly remove and assign values

Li={11,22,33,44}s=li.pop () print (s) {33}

12, remove( self * args,  * * kwargs): Remove the specified element does not exist the error

Li={11,22,33,44}s=li.remove (one) print (LI) {22,33,44}

symmetric_difference( self 13 . * args,  * * kwargs):   s=A.symmetric_difference(B)把A中有B中无得元素和B中有A中无得元素放到s中

Li={11,22,33,44}l2={11,55,66,77}s=li.symmetric_difference (L2) print (s) {33, 66, 44, 77, 22, 55}

14.symmetric_difference_update(self*args, **kwargs):   s=A.symmetric_difference_update(B)把A中有B中无得元素和B中有A中无得元素赋值给s

Li={11,22,33,44}l2={11,55,66,77}s=li.symmetric_difference_update (L2) print (LI) {22,33,44,55,66,77}

15.union(self*args, **kwargs): 并集

Li={11,22,33,44}l2={11,55,66,77}s=li.union (L2) print (s) {11,22,33,44,55,66,77}

16. update( self * args,  * * kwargs): The update does not generate a new collection

Li={11,22,33,44}l2={11,55,66,77}s=li.update (L2) print (LI) {11,22,33,44,55,66,77}

Exercises

# The original old_dict = {    "#1" in the database: {' hostname ': C1, ' Cpu_count ': 2, ' mem_capicity ':}, '    #2 ': {' hostname ': C1, ' Cpu_count ': 2, ' mem_capicity ': ' #3 ':    {' hostname ': C1, ' Cpu_count ': 2, ' mem_capicity ': +}   # CMDB new reported data New_dict = {
    "#1": {' hostname ': C1, ' Cpu_count ': 2, ' mem_capicity ': +}, '    #3 ': {' hostname ': C1, ' Cpu_count ': 2, ' mem_capicity ' :    "#4": {' hostname ': c2, ' Cpu_count ': 2, ' mem_capicity ': 80}}
M=set (Old_dict.keys ())
Print (m)
N=set (New_dict.keys ())
Print (n)

A=n.different to add (m)

B=m.different (n) to be removed

C=m that need to be updated.intersection(n)

Old_dict.update (a)

Print (old_dict)

Old_dict.pop (b)

Print (old_dict)

6, ternary operation (Trinocular operation), is the abbreviation for the simple conditional statement

Writing format: a= value 1 if condition else value 2 if the condition is true, assign value 1 to a condition not set to assign value 2 to a

A= "Lu" if 1>2 else "Xiao" print (a) Xiao

7, the depth of the copy

String (str) is created once and cannot be modified. As soon as you modify, create a new

List lists can record positions on and off

Numeric and string

Copy (regardless of depth) address is the same as long as it is assigned

Other data types

For dictionaries, Ganso, and lists, the change in memory address is different when assigning, shallow copy, and deep copy

assignment , just create a variable that points to the original memory address (the same memory address for the assignment), such as:

N1 = {"K1": "WU", "K2": 123, "K3": ["Alex", 456]}  n2 = N1

Shallow copy (just copy the outermost layer)

Import Copy  n1 = {"K1": "WU", "K2": 123, "K3": ["Alex", 456]}  n3 = Copy.copy (N1)

Deep copy recreate all data in memory (excluding the last layer, i.e., Python's internal optimization of strings and numbers) (copy all, except the bottom)

Import Copy  n1 = {"K1": "WU", "K2": 123, "K3": ["Alex", 456]}  n3 = Copy.copy (N1)

8. Functions

(Functional: A function code is encapsulated in a function, it is not necessary to repeat the writing, only the function can be called)

Define and use:

def function name (parameter):      ...    function Body    ...    return value

Characteristics

* def: a keyword that represents a function

* Function Name: Call function according to function name

* Parameters: Provide data for functions

* Function Body: A series of logical operations in a function

* Return value: Once the function has finished executing, you can return a value to the caller and the following program will not execute when the return value is encountered

Parameters (form parameter x and actual parameter (specific number))

#发送邮件实例
def email (): Import smtplib from Email.mime.text import mimetext from email.utils import formataddr msg = Mimetex T (' Mail content ', ' plain ', ' utf-8 ') msg[' from ' = Formataddr (["Wu Jianzi", ' [email protected] ') msg[' to '] = formataddr (["Leave", ' [email p Rotected] msg[' Subject '] = "subject" server = Smtplib. SMTP ("smtp.126.com") server.login ("[Email protected]", "email password") server.sendmail (' [email protected] ', [' [Email Protected] ',], msg.as_string ()) Server.quit ()
Email ()

The order in which parameters are passed in

def name (K1,K2,K3,K4):

Name (1,2,3,4) parameter, argument (default, in order) one by one corresponding relationship k1-1, k2-2, k3-3, k4-4

def name (K1, K2, K3, K4)

Name (k1=2,k2=1,k3=4,k4=3) specifies that the parameter is passed in to the argument, and can be specified in either order or

Default parameters

def a (p,name= "Lu Xiaojun"):       #假如函数中既有有默认值的参数, there are no default parameters, be sure to put the parameters without default values to the front        b=name + "drive to Xinjiang"    return BA () print (A ()           # A does not pass the parameters in the words default name= "Lu Xiaojun" Lu Xiaojun drive to Xinjiang

Dynamic Parameters ( I.)

def a (*b):        print (b) A (11,22,33,) (11,22,33) #传入 *b directly convert incoming to Ganso

Dynamic Parameters (Ii.)

Def  A (**b):    print (b) A (k1=123,k2=456) {' K2 ': 456, ' K1 ': 123} #传入 **b directly convert the incoming into a dictionary

Dynamic parameter combination (I and II)

Def  A (p,*b,**c):    print (p)    print (b)    print (c) A (11,22,33,k1=123,k2=456) 11
(22, 33) {' K1 ': 123, ' K2 ': 456}

General wording of parameters: *args **kwargs


Def A (*b): print (b) Li=[11,22,33]a (LI) ([One, All,],) #把li当成一个元素进行循环
List Def  A (*b):    print (b) li=[11,22,33]a (*li) (one, three, three) # *li: Loop li inside each element
Dictionary def  A (*b):    print (b) li={"K1": "V1", "K2": "V2"}a (LI) A (*li) ({' K1 ': ' v1 ', ' K2 ': ' V2 '},) (' K1 ', ' K2 ')

Dictionary (ii) def  A (**b):    print (b) li={"K1": "V1", "K2": "V2"}a (K1=li) A (**li) {' K1 ': {' K2 ': ' v2 ', ' K1 ': ' v1 '}}{' K2 ': ' v2 ' , ' K1 ': ' v1 '}

9, global variables, local variables (global variables are uppercase, local variables are lowercase)

a=456 #这里a是全局变量
Def dict (): a=123#这里的a是局部变量 The following print (a) cannot perform print (a) print (a) dict ()    

Modifying global variables with GLOBALS + global variables

A=123def dict ():    Global A    a=456dict () def Tim ():   print (a) Tim () 456

Exercises

1. The differences between common parameters, specified parameters, default parameters and dynamic parameters are briefly described.

The normal parameter is the user INPUT element in order one by one corresponding input

Specifies that the parameter is that the user can specify an element to be passed into a parameter, not in order

The default parameter is to specify a numeric value for the parameter in advance, if the user does not enter a value. Then the value specified by default is the parameter

A dynamic parameter is a plurality of elements that can receive input from the user, and the list is usually represented by *args, and the dictionary is usually *kwargs

2, write function, calculate the number of "number", "Letter", "space" and "other" in the incoming string

def m (p):    a=0    b=0    c=0 for    i in P:        if I.isdigit ():            a=a+1 for I in    P:        if I.isalpha ():            b=b+1 for    i in P:        if I.isspace ():            c=c+1    D=len (P)-(A+B+C)    return a,b,c,dq=m (p) print (q)

3, write function, to determine whether the user incoming objects (string, list, tuple) length is greater than 5.

Def z (P):    If Len (P) >5:        return True    else:        return Falsea =z (p) print (a)

4. Write function to check whether each element of the user's incoming object (string, list, tuple) contains a space.

def m (p): For    I in P:        if I.isspace ():            return True        else:            return falsez=m (p) print (z)

5, write the function, check the length of the incoming list, if greater than 2, then only the first two length of the content, and return the new content to the caller.

Def z (P):    If Len (P) >2:        S=p[0:2]        return s    else:        return falsem=z (p) print (m)

6. Write the function, check the element that gets all the odd bit indexes of the incoming list or tuple object, and return it to the caller as a new list.

Def z (P):    d=[] for    i in range (Len (P)):        if i%2==1:            d.append (P[i])    return dm=z (p) print (m)

7, write the function, check the length of each value passed into the dictionary, if greater than 2, then only the first two length of the content, and return the new content to the caller

Def z (P): For    I in P.values ():        If Len (i) >2:            M=i[0:2]    return mc=z (p) print (c)

Python Base Set

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.