python introduction learning experience 22.1.23

Chapter 6 dictionaries and collections

1. Concept and basic operation of Dictionary (get method)

A dictionary is a series of key value pairs

Access values, add key value pairs, modify values, and create empty dictionaries (users provide data or can automatically generate a large number of key value pairs)

Delete key value pair: del dictionary name [key name]

Dictionary composed of similar objects: common storage formats are as follows

rivers={'nile':'egypt',
        'yangtze':'china',
        'amazon':'brazil',      #A comma is also added after the last key value so that the key value can be added later
        }

Use the method get() to access the value:

. get (key, return value when it does not exist)

If the second parameter is not specified and the key does not exist, return None

print(alien_0.get('color','No'))    #If there is no key, the specified information is returned

2. Traverse the dictionary

(1). Traverse all key value pairs

Use two variables to store keys and values and reuse methods item() returns a list of key value pairs

for key,value in alien_0.items():   #~. item(): returns a list of key value pairs
    print(f"Key:{key}")
    print(f"Value:{value}\n")
    #If you traverse the dictionary directly, you will traverse all keys by default, and the effect is the same as ~ keys()

(2). Traverse all keys

Use a variable to store keys and reuse methods key() returns a list of keys

If you simply traverse the dictionary, you will traverse all keys by default. The effect is the same as using the method key(), but we should explicitly use the method key() for ease of understanding

(3). Traverse all keys in a specific order

The function sorted() can be called on the result of the dictionary method key()

(4). Traverse all values of the dictionary

Use a variable to store values and reuse methods value() returns a list of values

In this way, whether to duplicate or not is not considered. In order to eliminate duplicate items, set can be used

3. Assembly

(1). Basic concepts of sets

The set() function finds the unique elements in the list and creates a collection

Collection support:

① Member operation symbol (i.e. in) ② for loop ③ len() get set length ④ clear() clear the collection

Instead of: index, slice, join, duplicate

(2). How empty sets are defined

Pay attention to the difference between empty dictionary definition and empty dictionary definition

s = set([])     #Empty set definition
sl = {}         #Comparison: empty dictionary definition 

(3). List de duplication method

First convert the list into a set, remove the duplicate by using the feature of set de duplication, and then convert it into a list

li = [1,2,3,1,1,2,3]
print(list(set(li)))    #List de duplication: convert it to set type de duplication, and then convert it to list type output

(4). Add / delete elements

s = {6,7,8,9}
s.add(1)            #Add an element
s.update({5,3,2})    #Add several elements
s.remove(1)          #Delete the specified element in the collection. If the element does not exist, an error will be reported
s.discard(10)        #Deletes the specified element in the collection. If the element does not exist, nothing is done
s.pop()              #Randomly delete an element in the collection and return the deleted element

(5). Intersection union difference set

4. Nesting of dictionaries

(1). Dictionary list

That is, the elements of the list are dictionaries, which are easy to use loops, slices or if statements

(2). Store list in dictionary

That is, the value of the dictionary key is a list

(3). Store dictionary in dictionary

That is, the value of the dictionary key is a dictionary. The following is an example

Note: when the dictionary is stored in the dictionary, the reading method shall be considered when reading

cities={
    'sh':{'country':'china','rank':'NO1'},
    'ny':{'country':'america','rank':'NO2'},
    'bj':{'country':'china','rank':'NO3'},
    }
​
for city,info in cities.items():
    print(f"{city.upper()} is in {info['country'].title()}, and it ranks {info['rank']}.")

Chapter 7 user input and while loop

1. Get user input

(1). Function input()

prompt can be displayed after user input

Syntax: a = input("prompt content")

+=Operator can add another string to the end of the string

message=input("Tell me sth:")   #prompt in parentheses
print(message)
​
prompt="Please tell me ..."
prompt+="\nWhat's your name? "  #New operator+=
name=input(prompt)
print(name.title())

(2). Use int() to get numeric input

The default string returned by the function input() can be converted to numeric input using int()

2.while loop

(1). Basic syntax format

Note that the line of the while statement should end with a colon (the same as the for statement and if statement)

You can define a flag and specify the trigger condition in the loop section to judge whether the while loop continues

Define a variable
while + Condition test :
    Cyclic code block

(2). Implement command line prompt

① break: jump out of the whole loop and no subsequent content of the loop will be executed

② Continue: jump out of this loop. The code after continue will no longer be executed, but the loop will continue

③ exit(): ends the program

current_number=0
while current_number < 10:
    current_number += 1
    if current_number % 2 == 0:
        continue                    #Skip even
    print(current_number)

(3). Use the while loop to process lists and dictionaries

The for loop is an effective way to traverse the list, but the list should not be modified in the for loop, otherwise it will be difficult to track the elements in the period

By combining while loops with lists and dictionaries, you can collect, store, and organize large amounts of input for subsequent viewing and display

It can be used to move elements between lists, delete all list elements with specific values (using remove), and populate the dictionary with user input (using flag)

Chapter 8 functions

1. Basic grammar format

Note: def colon document string indents formal parameters and arguments

The return value can be set, and its data type can be string or dictionary

You can modify the list through functions

If you do not want the function to modify the list, you can pass a copy of the list to the function (that is, slice [:]), so that the original list will not be affected

Generally, you should not pass copies because the time and memory spent creating copies will reduce efficiency

def favorite_book(book):
    """Show favorite book titles"""          #Document string (comment)
    print(f"My favorite book is {book.title()}")
    return xxx              #Some functions have return values
​
favorite_book('love')

2. Method of passing arguments

(1). Position argument

That is, according to the default corresponding order

(2). Keyword argument

When calling a function, specify the formal parameters corresponding to each argument

describe_pet(pet_name='harry',pet_type='hamster')
describe_pet(pet_type='hamster',pet_name='harry')       #The two are equivalent, regardless of order

(3). Default value

You can specify the default value in the formal parameter list, simplify the function call and point out the typical usage of the function

The default value must be placed at the end of the formal parameter list; If you want to put it in the middle, it should be separated by an asterisk

Setting the default value to an empty string makes the argument "optional"“

3. Pass any number of arguments

(1). Use a combination of positional arguments and any number of arguments

Add an asterisk before the formal parameter name, eg: def pizza(*toppings):

An asterisk indicates that python creates a new meta group named parameter name, encapsulates all values in this tuple, and then recycles the execution of the function

If you want to accept different types of arguments, the asterisk parameter must be placed last. python will first match the position parameter and keyword parameter, and then collect the remaining arguments into the asterisk parameter eg: def pizza(size,*toppings):

The generic parameter name * args indicates that any number of location arguments are collected

(2). Use any number of keyword arguments

Can accept any number of key value pairs

Two asterisks indicate that you want python to create a named user_info, and put the received key value pairs into this dictionary

The generic parameter name * * kwargs indicates that any number of keyword arguments are collected

def build_profile(first,last,**user_info):
    """Create a dictionary that contains everything we know about users"""
    user_info['first_name'] = first
    user_info['last_name'] = last
    return user_info
​
user_profile = build_profile('albert','einstein',
                            location='princeton',       #Note that the location here is not quoted
                            field='physics')
print(user_profile)

4. Store functions in modules

Store the function in a separate file called module, and then import the module into the main program. The module has an extension of py file

The import statement allows the code in the module to be used in the currently running program

(1). Import the entire module

Direct import + file name eg: import pizza

To call the function of the imported module, specify the module name and function name, separated by a period eg: pizza make_ pizza()

(2). Import specific functions

Syntax: from module_ name import function_ 0, function_ 1, function_ two

There is no need to add a period when calling the function, because the function is explicitly imported in the import statement

(3). Use as to assign an alias to a function

eg: from pizza import make_pizza as mp

At this point, you only need mp() to call the function

(4). Alias the module using as

eg: import pizza as p

At this point, you only need p.make to call the function_ pizza()

(5). Import all functions in the module

Using the asterisk (*) operator allows python to import all functions in the module

eg: from pizza import *

5. Function writing specification

① When naming functions and modules, use only lowercase letters and underscores

② Function functions should be briefly explained in the document string

③ When specifying default values for formal parameters, and keyword arguments when calling functions, there should be no spaces on both sides of the equal sign

④ The length of the code line should not exceed 79. Enter the left parenthesis in the function definition, press enter, and press Tab twice to distinguish the formal parameter list from the function body indented one layer only

⑤ When writing multiple functions, there are two blank lines between each function for easy distinction

⑥ All import statements should be placed at the beginning of the file, unless comments are used at the beginning of the file to describe the whole program

Today's notes

a=car = = 'bmw' first execute the condition test, and then assign True or False to a

Shift+Alt+E} you can directly run a selected piece of code

Keywords: Python

Added by knashash on Mon, 24 Jan 2022 23:07:32 +0200