Python learns the nineth day, constructs the dictionary processing data, assigns the value separately, enters the Chinese comma .... function First Knowledge

Source: Internet
Author: User

1. Create a dictionary {}, enhance the judgment, process the data

List3 = [{"Name": "Alex", "hobby": "Smoking"},         {"name": "Alex", "hobby": "Drink"},         {"name": "Alex", "hobby": "Perm"},         {  "Name": "Alex", "Hobby": "Massage"},         {"name": "Wusir", "hobby": "Shout Wheat"},         {"name": "Wusir", "hobby": "Hip Hop"},]list4 = []dic = {}for i in List3:    if i[' name '] not in dic:        dic[i[' name '] [{' Name ': i[' name '], ' hobby_list ': [i[' Hobby ']]}< C8/>else:        dic[i[' name ']][' hobby_list '].append ([i[' hobby ']]) List4 = List (Dic.values ()) print (LIST4)

Increase in Dictionary:

DIC = {}

dic[' name] = ' Alex ' (directly added a key-value pair)

Assign values separately:

1. For tuples, lists can be assigned values individually

List1 = [1,2,3]a,b,c = List1print (a,b,c) #1 2 3list2 = [($), (' A ', ' B ')]e,f = List2print (e,f) # (1, 2) (' A ', ' B ') H,i = Eprin T (h,i) #print (h,i)

2. Dictionary Dict.items ()

Dict.keys ()

Dict.values () can be assigned separately

DIC = {' name ': ' Alex ', ' hobby ': ' girl '}a,b = Dic.keys () List2 = List (Dic.keys ()) print (A, b) #name hobby print (list2) #[' name ' , ' hobby ']c,d = Dic.values () print (c,d) #alex girle,f = Dic.items () List1 = List (Dic.items ()) print (e,f) # (' Name ', ' Alex ') (' Hobby ', ' Girl ') print (List1) #[(' name ', ' Alex '), (' Hobby ', ' girl ')]

File operation:

Write in W mode: only String types can be written

Writelines, the contents of the list can be output as a string (only strings in the class table)

With open (R ' a.txt ', mode= ' W ', encoding= ' utf-8 ') as F:    f.write (' Alex ')    f.writelines ([' 1 ', ' 2 '])

function First Knowledge:

def func ():--------> Function names to be recognizable

Pass

Return--------> returned value of function

Func ()--------------> function invocation (execution)

Role of the function:

Encapsulates a feature

Advantages of the function:

Reduce the repetition rate of code

Enhance the readability of your code

------encounters a return in the function body:

1. Direct End

2. Return value when calling function: (3 cases)

A. Return is empty-----> return None

def func ():    a = 1    b = [up]    Returnfunc () print (func ()) #None

B.return followed by 1 values-----What type of a is followed by >return and what type is it?

def func ():    a = 1    b = [+]    return Afunc () print (func ()) #1

C.return followed by multiple values-----> returns a tuple

def func ():    a = 1    b = [+]    return A,bfunc () print (func ()) # (1, [1, 2])
#函数中尽可能不要哦出现print ()
The #print (func) prints the ID address

Form participation arguments:

def func ():-------> Parameters

Pass

Return

Func ()--------------> arguments

  

Actual parameters:

1. Position arguments, one by one corresponding

2. Keyword arguments, which can be out of order, but require one by one to correspond

3. Mixed arguments, positional arguments must be in front

def func1 (x, y):    return x + yname = 1 func1 (name,y=100,) #name is the positional argument print (Func1 (name,y=100))

Formal parameters:

1. Position line parameter, must one by one corresponding

def func1 (x, Y, z):    print (x, y, z) func1

2, default line parameter, general unchanged, can be re-assigned at argument

def func1 (x,y,a=666): # a=666 is the default parameter is generally immutable data type    print (x,y,a) func1 (min) # no value, no error func1 (1,2,333) # 333 can overwrite 666

The data for the default parameter is generally immutable, and the ID is constant in the case of a mutable data type (e.g. [], when it is a list)

#必考的面试题:d EF func1 (x,l1=[]): #默认参数如果是可变的数据类型, the ID of this data is constant    l1.append (x)    return l1ret = func1 (1) Print (Ret,id (ret)) Ret1 = func1 (+) print (Ret1,id (RET1))

3. Dynamic parameters: *args and **kwargs make the function extensible

Args and (*args,**kwargs)

The former represents 1 positional parameters

The latter * and * * represent aggregation, args and Kwargs, which are conventionally

*args aggregates the positional parameters in the argument into a tuple and assigns the tuple to args (that is, args is a tuple)

**kwargs aggregates the key arguments in the argument into a dictionary and assigns the dictionary to Kwargs (that is, Kwargs is a dictionary)

Universal Addition Calculator:

def sum1 (*args,**kwargs):    sum2 = SUM (args)    return Sum2print (Sum1 (1,2,3,4,55,))

* and * * 's Magic Usage:

1. When defining a function, * and * * Play the role of aggregation

2. When calling a function, * and * * play a role. ---> in the argument * and * * Can break up later iterations of the object, then assemble into a tuple, or a dictionary

L1 = [1,2,3,4]L2 = [5,6,7,8,9]def func1 (*args,**kwargs):    print (args) func1 (*L1,*L2)
# (1, 2, 3, 4, 5, 6, 7, 8, 9)
L1 = {' A ': 1, ' B ': 3}l2 = {' C ': 2, ' d ': 4}def func1 (*args,**kwargs):    print (Kwargs) func1 (**L1,**L2) #{' a ': 1, ' B ': 3, ' C ': 2 , ' d ': 4}

Positional parameters, default parameters, dynamic position parameters (*args), dynamic default parameters (**kwargs) in the parameter placement order

  

def func (A,b,*args, ' age ' =18,**kwargs): Pass

Start at the end:
Range (10) starting from 0 Gu Tou disregard tail 0-->9
Index () starting from 0
Len () starting from 1
Enumerate () starting from 0, mainly for the list (can iterate objects)

Python learns the nineth day, constructs the dictionary to process the data, assigns the value separately, enters the Chinese comma .... function First Knowledge

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.