catalogue
1. Conditional judgment statement
If else double branch statement:
Multi branch if elif else statement:
9.break, continue and pass statements
2. Characteristics of dictionary
4. Common methods of dictionary
1. Notes
- Single-Line Comments : Start with # and everything on the # right serves as a description, rather than the program to be executed, as an auxiliary description
# I'm a comment. You can write some function descriptions in it print('hello world')
- multiline comment : Start with three single quotation marks' 'and end with three single quotation marks'', and put the comment in the middle
''' I'm a multiline comment, You can write many lines of function descriptions ''' print('hello world')
2. Variables and types
Variables can be any data type and are represented by a variable name in the program
The variable name must be composed of upper and lower case English, numbers and underscores, and cannot start with a number
a = 1 # The variable a is an integer test_007 = 'Test_007' # Variable test_007 is a string
Assignment: for example, a = "ABC", the Python interpreter does two things
- A string of "ABC" is created in memory
- Create a variable named a in memory and point it to "ABC"
3. Keyword (identifier)
1. What are keywords?
Some identifiers with special functions in Python are the so-called keywords. Python has already used them, so developers are not allowed to define identifiers with the same name as keywords
2. View keywords
>>> import keyword >>> keyword.kwlist
3. Keywords
['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']
4. Format output
1. What is formatting?
See the following code:
age = 10 print("I this year%d year"%age) age = 18 name = "xiaohua" print("My name is%s,Age is%d"%(name,age))
In the program, I see an operator like% which is the formatted output in Python
2. Common format symbols
Format symbol | Conversion meaning |
%c | character |
%s | Format through str() string conversion |
%i | Signed decimal integer |
%d | Signed decimal integer |
%u | Unsigned decimal integer |
%o | Octal integer |
%x | Hexadecimal integer (lowercase) |
%X | Hexadecimal integer (uppercase letter) |
%e | Index symbol (lowercase e) |
%E | Index symbol (capital E) |
%f | Floating point real number |
%g | %Abbreviations for f and% e |
%G | %Abbreviations for f and% E |
3. Special output
Code example:
print("aaa","bbb","ccc") # Printout with spaces between values and no line breaks print("www","baidu","com",sep=".") # Printout, values are connected by dots without line breaks print("hello",end="")# Printout, values are not separated and do not wrap print("world",end="\t") # Printout with values separated by a tab without line breaks print("python",end="\n") # Printout with values separated by a newline print("end")
aaa bbb ccc www.baidu.com helloworld python end
4. Line feed output
When outputting, if there is \ n, the content after \ n will be displayed on another line
print("1234567890-------") # Will be displayed on one line print("1234567890\n-------") # One line shows 1234567890 and the other line shows-------
5. Input
What is put in the parentheses of input() is the prompt information, which is used to give a simple prompt to the user before obtaining the data
After obtaining data from the keyboard, input() will be stored in the variable to the left of the equal sign
password = input("Please input a password:") print('The password you just entered is:', password)
Operation results:
Please input a password! one hundred and twenty-three thousand four hundred and fifty-six The password you entered is 123456
Note: the input() function must accept an expression
6. Judge variable name type
Put the variable name in parentheses in the type() function and return the type of the variable name
a=100 print(type(a))
Operation results:
<class 'int'>
7. Operator
8. Process control statement
1. Conditional judgment statement
if branch statement:
Syntax format:
if Conditions to judge: # Execute statement
Code example:
age = 30 print "------if Judgment start------" if age>=18: print "I'm an adult" print "------if End of judgment------"
If else double branch statement:
Syntax format:
if Conditions to judge: # Execute statement 1 else: # Execute statement 2
Code example:
if True: print ("Answer") print ("True") else: print ("Answer") print ("False") # Inconsistent indentation will lead to running errors
Multi branch if elif else statement:
Syntax format:
if Expression 1: # Execute statement 1 elif Expression 2: # Execute statement 2 elif Expression 3: # Execute statement 3 elif expression n: # Execute statement n else : # Execute statement n+1
Code example:
score = 77 if score>=90 and score<=100: print('This examination, the grade is A') elif score>=80 and score<90: print('This examination, the grade is B') elif score>=70 and score<80: print('This examination, the grade is C') elif score>=60 and score<70: print('This examination, the grade is D') else: #elif can be used with else print('This examination, the grade is E')
if nesting:
Syntax format:
if Expression 1: # Execute statement 1 ...(ellipsis)... if Expression 2: # Execute statement 2 ...(ellipsis)...
Code example:
xingBie = 1 # Use 1 for boys and 0 for girls danShen = 1 # Use 1 for single and 0 for boyfriend / girlfriend if xingBie == 1: print("It's a boy") if danShen == 1: print("Shall I introduce you to one?") else: print("Can you introduce one to me?") else: print("Are you a girl") print("......")
be careful:
- If judgment of the outer layer can also be if else
- The inner if judgment can also be if else
- Select according to the actual development situation
2. Circular statement
for loop
Syntax format:
for Temporary variable in List or string, etc: # Code executed when the loop satisfies the condition
Code example:
# From [0,5) interval, from 0 to 5, the default step value is 1, and the data is retrieved for i in range(5): print(i) # Loop out the value of the variable name name = 'chengdu' for x in name: print(x) # From [0,10), starting from 0 and ending at 12, the step value is 3 for a in range(0,12,3): print(a) # Fetch elements from array a = ["aa","bb","cc","dd"] for i in range(len(a)): print(i,a[i])
while Loop
Syntax format:
while expression: # Execute statement
Code example:
i = 0 while i<5: print("The current is the second%d Execution cycle"%(i+1)) print("i=%d"%i) i+=1
While else loop
Syntax format:
while expression: # Execute statement 1 else: # Execute statement 2
Code example:
count = 0 while count<5: print(count,"Less than 5") count+=1 else: print(count,"Greater than or equal to 5")
practice:
1. Calculate the sum of 1 ~ 100 (including 1 and 100)
# Mode 1: n= 100 a=1 sum = 0 while a<=n: print("The first%d Perform addition"%a) sum = sum + a a+=1 print("1 reach%d The sum of is:%d"%(n,sum)) # Mode 2: i=1; n=101 sum = 0; for i in range(i,n,1): sum = sum + i print("%d reach%d The sum of is:%d"%(i-99,n-1,sum))
2. Print 99 multiplication table
# Mode 1: a=1 while a< 9: a = a + 1 b = 1 while b<=a : print("%dx%d=%d"%(b,a,a*b),end=" ") b = b+1 print("",end="\n") # Mode 2: for i in range(1,10): # print(i,end = ' ') for j in range(1,i+1): print('%s*%s=%s' %(i,j,i*j),end = ' ') print()
9.break, continue and pass statements
- The break statement can jump out of the loop body of for and while
i = 0 while i<10: i = i+1 print('----') if i==5: break print("current i The value of is%d"%i) print(i)
- continue statement skips the current cycle and directly enters the next cycle
i = 0 while i<10: i = i+1 print('----') if i==5: continue print("current i The value of is%d"%i) print(i)
- pass is an empty statement, which is generally used as a placeholder statement and does nothing
10. Escape character
Escape character | describe |
\ | Backslash symbol |
' | Single quotation mark |
" | Double quotation mark |
\a | Ring the bell |
\b | Backspace |
\000 | empty |
\v | Vertical tab |
\t | horizontal tab |
\r | enter |
\f | Page change |
\oyy | Octal number, yy represents the character, for example: \ o12 represents line feed, where o is a letter, not a number 0 |
\xyy | Hexadecimal number, yy represents the character, for example: \ x0a represents line feed |
\other | Other characters are output in normal format |
11.import and from... import
In Python, use import or from... Import to import the corresponding library or module
Import the whole module in the format:
import somedule
Import a function from a module in the following format:
from somemodule import somefunction
Import multiple functions from a module in the format
from somemodule import firstfunc, secondfunc,thirdfunc
Import all functions in a module in the following format:
from somemodule import \*
Code example:
import random # Import random library a = random.randint(0,2) #Randomly generate a number of 0, 1 and 2 and assign it to variable a
Exercise:
Use the relevant knowledge of if statement to realize the effect of stone scissors cloth game
Please enter: Scissors (0), stone (1), cloth (2):_
The user inputs one of the numbers 0-2 and gives the result information after comparing it with the number randomly generated by the system
Code example:
# Mode 1: import random a = input("Game participants") print("Game participants enter: %s",a)1 b = random.randint(0,2) print(b) if a=="stone" or a=="scissors" or a=="cloth": print("Your input is correct!") if a=="scissors": a = 0 elif a=="stone": a = 1 elif a == "cloth": a = 2 if a>b: print("Participant wins") elif a=b: print("it ends in a draw") else: print("Robot wins") else: print("Your input is incorrect, please input as required") # Mode 2: import random person =int(input("please enter:[0:Scissors 1:Stone 2:cloth] ")) computer = random.randint(0,2) print("Computer punch: %d"%computer) if person > 2: print("enter wrong") elif person == 0 and computer ==2: print("good you win ") elif person == 1 and computer == 0: print("good you win ") elif person == 2 and computer == 1: print("good you win") elif person == computer : print("oh no Tie") else: print("your lose")
12. Core data types of Python
1. String
1. String format
# Mode 1: word = 'character string' # Mode 2: sentence = "It will be a sentence" # Mode 3: parapraph = """ It's no use thinking about it. It's practical! """ print(word) print(sentence) print(parapraph)
2. String method
Serial number | method | describe |
1 | capitalize() | Converts the first character of a string to uppercase |
2 | center(width, fillchar) | Returns a string centered on the specified width. fillchar is the filled character. The default is space. |
3 | count(str, beg= 0,end=len(string)) | Returns the number of occurrences of str in a string. If beg or end is specified, returns the number of occurrences of str in the specified range |
4 | bytes.decode(encoding="utf-8", errors="strict") | There is no decode method in Python 3, but we can use the decode() method of bytes object to decode a given bytes object, which can be encoded and returned by str.encode(). |
5 | encode(encoding='UTF-8',errors='strict') | Encode the string in the encoding format specified by encoding. If there is an error, an exception of ValueError will be reported by default, unless the errors specify 'ignore' or 'replace' |
6 | endswith(suffix, beg=0, end=len(string)) | Check whether the string ends with obj. If beg or end is specified, check whether the specified range ends with obj. If yes, return True; otherwise, return False |
7 | expandtabs(tabsize=8) | Turn the tab symbol in the string into a space. The default number of spaces for the tab symbol is 8 |
8 | find(str, beg=0, end=len(string)) | Check whether str is included in the string. If the specified range is beg and end, check whether it is included in the specified range. If it is included, return the starting index value, otherwise return - 1 |
9 | index(str, beg=0, end=len(string)) | It is the same as the find() method, except that if str is not in the string, an exception will be reported |
10 | isalnum() | Returns True if the string has at least one character and all characters are letters or numbers, otherwise returns False |
11 | isalpha() | Returns True if the string has at least one character and all characters are letters, otherwise returns False |
12 | isdigit() | Returns True if the string contains only numbers; otherwise, returns False |
13 | islower() | Returns True if the string contains at least one case sensitive character and all of these (case sensitive) characters are lowercase; otherwise, returns False |
14 | isnumeric() | Returns True if the string contains only numeric characters, otherwise False |
15 | isspace() | Returns True if the string contains only white space; otherwise, returns False |
16 | istitle() | Returns True if the string is captioned (see title()), otherwise returns False |
17 | isupper() | Returns True if the string contains at least one case sensitive character and all of these (case sensitive) characters are uppercase; otherwise, returns False |
18 | join(seq) | Use the specified string as the separator to merge all elements (string representation) in seq into a new string |
19 | len(string) | Return string length |
20 | [ljust(width, fillchar]) | Returns a left aligned original string and fills it with a new string of length width with fillchar. Fillchar defaults to space. |
21 | lower() | Converts all uppercase characters in a string to lowercase |
22 | lstrip() | Truncate the space to the left of the string or the specified character |
23 | ITmaketrans() | Create a character mapping conversion table. For the simplest call method that accepts two parameters, the first parameter is a string, which represents the character to be converted, and the second parameter is also a string, which represents the target of conversion. |
24 | max(str) | Returns the largest letter in the string str |
25 | min(str) | Returns the smallest letter in the string str |
26 | [replace(old, new , max]) | Replace str1 in the string with str2. If max is specified, the replacement shall not exceed max times |
27 | rfind(str,beg=0,end=len(string)) | It is similar to the find() function, but it starts from the right |
28 | rindex( str, beg=0, end=len(string)) | Similar to index(), but starting from the right |
29 | [rjust(width, fillchar]) | Returns a right justified original string and fills the new string with fillchar (default space) to length width |
30 | rstrip() | Delete spaces at the end of the string |
31 | split(str="", num=string.count(str)) num=string.count(str)) | Take str as the separator to intercept the string. If num has a specified value, only num+1 substring will be intercepted |
32 | [splitlines(keepends]) | Separated by rows ('\ r', '\ r\n', \ n '), a list containing rows as elements is returned. If the parameter keepers is False, the line break character is not included. If it is True, the line break character is retained |
33 | startswith(substr, beg=0,end=len(string)) | Checks whether the string starts with the specified substring substr. If yes, it returns True, otherwise it returns False. If beg and end specify values, it checks within the specified range |
34 | [strip(chars]) | Execute lstrip() and rstrip() on the string |
35 | swapcase() | Converts uppercase to lowercase and lowercase to uppercase in a string |
36 | title() | Returns a "captioned" string, that is, all words start with uppercase and the rest are lowercase (see istitle()) |
37 | translate(table, deletechars="") | Convert the characters of string according to the table given by str (including 256 characters), and put the characters to be filtered into the deletechars parameter |
38 | upper() | Converts lowercase letters in a string to uppercase |
39 | zfill (width) | Returns a string with a length of width. The original string is right aligned and filled with 0 |
40 | isdecimal() | Check whether the string contains only decimal characters. If so, return true; otherwise, return false |
Code example:
str='chengdu' print(str) # Output string print(str[0:-1]) # Output all characters from the first to the penultimate print(str[0]) # First character of output string print(str[2:5]) # Output characters from the third to the fifth print(str[2:]) # Output all characters starting from the third print(str * 2) # Output string twice print(str + 'Hello') # Connection string print(str[:5]) # Output all characters before the fifth letter print(str[0:7:2]) # [start: end: step size] print('------------------------------') print('hello\nchengdu') # Escape special characters with backslash (\) + n print(r'hello\npython') # Add an r before the string to represent the original string without escape
2.List
1. Definition of list
Variable name = [Element 1,Element 2, element 3,....]
Code example:
# Definition of list namesList = ['xiaoWang','xiaoZhang','xiaoHua'] # Extract elements from the list by index print(namesList[0]) print(namesList[1]) print(namesList[2]) # Extract the elements in the list through the for loop for name in namesList: print(name)
2. Precautions for list:
- The list is written between square brackets [] and the elements are separated by commas
- The list index value starts with 0 and - 1 is the starting position from the end
- The types of elements in the list can be different. It supports numbers, strings, and even lists (so-called nesting)
- The list can be spliced with the + operator, and * indicates repetition
3. Common methods of list
Note: index represents index and value represents element
method | Operation name | Explain operation |
list[index] | Accessing elements in a list | Direct access to elements in the list through Subscripts |
list[start: end: length] | Slice of list | Use [start subscript index: end subscript index: step value], and note that the range interval is "closed left and open right" |
for i in list:print(i) | Traverse list elements | for loop |
list.append(values) | [add] append data to the end of the list | Appends the new element value to the end of the current list |
list.extend(list1) | Add list | Adds elements from other lists to the current list |
list.insert(index,value) | [add] list data insertion | Inserts an element at a specified location based on the given index |
del list[index] list.remove(value) | Delete: delete the list | del: we delete the element at the specified position through the index. remove: removes the first matching value of the specified value in the list. If it is not found, it will throw an exception |
list.pop() | Click Delete to open the element at the end of the list | Pop up the element at the end of the current list, which is equivalent to deleting the element |
list[index] = 8 | [change] update the data in the list | Modify the specified element by subscript |
value in list value not in list | [query] list membership | in not in |
list.index(value,start,end) | [query] list membership | Find out whether the specified element exists in the list, and the subscript of the returned element exists. If it cannot be found, an error will be reported. Note that the range is "closed on the left and open on the right" |
list.count(value) | [query] find the number of occurrences of elements | Counts the number of occurrences of the specified element in the current list |
list3 = list1 +list2 | Addition operation of list | + |
list.sort() | Sort list | Sorts the current list elements |
list.reverse() | Inversion of [row] list | Inverts all elements of the list |
len() | Get list length | Gets the current list length |
max() | Gets the maximum value of the list element | Gets the maximum value of the list element |
min() | Gets the minimum value of the list element | Gets the minimum value of the list element |
list() | Convert other types of objects to lists | Convert other types of objects to lists |
Code example:
# -*- codeing = utf-8 -*- # @Time :2020/9/14 20:08 # @Author:qzp # @File : demo2-1.py # @Software: PyCharm # List definition namelist = ["Xiao Zhang","Xiao Wang","petty thief","qzp","wjw"] print(namelist[0]) print(namelist[0:2:1]) # List slice namelist.append("tail") # List element append list1 = ["list1"] namelist.extend(list1) # Append list elements namelist.insert(0,"King") # List element insertion for name in namelist: print(name) del namelist[5] # Deletes the element of the specified index namelist.remove("qzp") # Deletes the specified element for name in namelist: print(name) findName = input("Please enter the name you want to find") if findName in namelist: # Finds whether the specified element exists in the list element print("Congratulations on finding the name you need") else: print("Unfortunately, I didn't find it") a = ["a","b","d","c","g","f"] print(a.index("a", 0, 5)) # Find out whether the specified element exists in the list. If the index of the returned element exists, an error will be reported a.reverse() # Invert list elements print(a) a.sort() # Ascending list elements print(a) a.sort(reverse = Ture) # Descending list elements print(len(a)) # Get list length
4. List nesting
The element in a list is a list, that is, list nesting. To put it bluntly, it is a two-dimensional array.
# Definition of nested list: schoolNames = [['Peking University','Tsinghua University'],['Nankai University','Tianjin University','Tianjin Normal University'],['Shandong University','Ocean University of China']] # List nested fetch element print(schoolNames[0][0])
5. Application exercise:
There are 3 offices in a school. Now there are 8 teachers waiting for the assignment of stations. Please write a program to complete the random assignment
Code example:
#encoding=utf-8 import random # Define a list to hold 3 offices offices = [[],[],[]] # Define a list to store the names of 8 teachers names = ['A','B','C','D','E','F','G','H'] i = 0 for name in names: index = random.randint(0,2) offices[index].append(name) i = 1 for tempNames in offices: print('office%d The number of people:%d'%(i,len(tempNames))) i+=1 for name in tempNames: print("%s"%name,end='') print("\n") print("-"*20)
3.Tuple (tuple)
1. Definition of tuple
Tuple is similar to list, except that the elements of tuple are written in parentheses, and the elements are separated by commas.
- Create empty tuple
tupl = () # Judgment type print(type(tup1)) # Running result: < class' tuple '>
- Definition of tuples
tup2 = (50,) # Add a comma and the type is tuple print(type(tup2)) # Output: < class' tuple '> tup3 = (50) # The type is integer without comma print(type(tup3)) # Output: < class' Int '>
Note: to define a tuple with only one element, you must add a comma
2. Tuple access
tup1 = ('Google', 'baidu', 2000, 2020) tup2 = (1, 2, 3, 4, 5, 6, 7 ) print ("tup1[0]: ", tup1[0]) print ("tup2[1:5]: ", tup2[1:5])
Operation results:
tup1[0]: Google tup2[1:5]: (2, 3, 4, 5)
3. Common methods of tuples
method | Operation name | Explain operation |
tuple[index] | Accessing elements in tuples | Accessing elements in tuples through Subscripts |
for i in tuple:print(i) | Traversal tuple | for loop |
tuple[start: end: length] | Slice of tuples | Use [start subscript index: end subscript index: step value], and note that the range interval is "closed left and open right" |
value in tuple value not in tuple | Tuple membership | in not in |
tuple.count(value) | [query] find the number of occurrences of elements | Counts the number of occurrences of the specified element in the current tuple |
tuple3 = tuple1+tuple2 | Addition operation of tuples | New method of tuple |
len() | Get tuple length | Get tuple list length |
max() | Gets the maximum value of the tuple element | Gets the maximum value of the tuple element |
min() | Gets the minimum value of the tuple element | Gets the minimum value of the tuple element |
tuple() | Convert objects of other types to tuples | Convert objects of other types to tuples |
Code example:
# -*- codeing = utf-8 -*- # @Time :2020/9/15 19:49 # @Author:qzp # @File : deom2-4.py # @Software: PyCharm tup1 = (1,2,3,4,5) # increase tup2 = ("qzp","wjw") tup3 = tup1 + tup2 # Recreate a new tuple print(tup3) # Delete del tup3 # Delete the entire tuple variable, not just the elements in the tuple print(tup3) # After deletion, an error will be printed: name 'tup3' is not defined # check print(tup1[0]) print(tup2[1]) # change tup1[0] = 100 # An error is reported and cannot be modified
Notes for summarizing tuples:
- To define a tuple with only one element, you must add a comma
- The element of a defined tuple cannot be modified, but it can contain objects, such as list
- When deleting, the whole tuple is deleted, not the elements in the tuple
4.dict (Dictionary)
1. Definition of dictionary
A dictionary is an unordered collection of objects. It is stored using key value pairs and has a very fast search speed
# The variable info is of dictionary type info = {'name':'monitor', 'id':100, 'sex':'f', 'address':'Earth Asia Beijing, China'}
2. Characteristics of dictionary
- Dictionaries, like lists, can store multiple data
- Each element of the dictionary consists of two parts, key: value. For example, 'name': 'monitor', 'name' is the key and 'monitor' is the value
- In the same dictionary, the key must be unique
- The key must be of immutable type
3. Access to dictionaries
info = {'name':'qzp','age':24} print(info['name']) # Get name print(info['age']) # Get age print(info.get('sex')) # Get the nonexistent key, get the empty content, and return none without exception print(info.get('sex','male')) #If you get empty content through key, you can set the default value to return. If you get non empty content, you will return the obtained value
If you access a nonexistent primary key, the following error will be reported:
print(info['sex']) # An exception occurs when a nonexistent key is obtained Traceback (most recent call last): File "C:/Users/Administrator/PycharmProjects/pythonProject/demo1.py", line 4, in <module> print(info['sex']) # An exception occurs when a nonexistent key is obtained KeyError: 'sex'
4. Common methods of dictionary
method | Operation name | Interpretation method |
dict[key] | Accessing elements in a dictionary | If the key does not exist, an exception will be thrown |
dict.get(key) | Accessing elements in a dictionary | Through the get method, None is returned and no exception is thrown |
for key in dict: print(key,dict[key]) | Traversal dictionary | Through the for loop, only keys can be obtained. values need to be obtained using dict[key] |
for key,value in dict.items():print(key,value) | Traversal dictionary | Use the items method to obtain the key and value |
dict.keys() dict.values() dict.items() | Get all key s Get all value s Get all key values | Using the keys and values methods |
dict[key] = newvalue | Modify value | Modify value directly through key |
dict[newkey] = newvalue | New key value pair | Direct addition |
del dict[key] | Delete dictionary element | Delete dictionary elements through key |
dict.pop(key) | Pop up dictionary element | Pop up dictionary elements through key |
key in dict | Determine whether the key exists | in |
dict.update(dict2) | Merge dictionary | |
dict(zip(list1,list2)) | Convert a list into a dictionary | Turn two lists into dictionaries |
dict2 = dict([['key1','value1']]) | Turn a nested list into a dictionary | Turn a nested list into a dictionary |
dict.clear() | Clear elements in dictionary | Clear elements in dictionary |
Code example:
info = {'name':'qzp','age':'24','sex':'male'} # check print(info['name']) # Get value based on primary key print(info['age']) print(info['sex']) for i in info: # Traversal can only get the primary key print(i) print(info.keys()) # Get a list of all primary keys: dict_keys(['name', 'age', 'sex']) print(info.values()) #Get a list of all values: Dict_ Values (['qzp ',' 24 ',' male ']) print(info.items()) #Get all item lists Dict_ Items ([('name ',' QzP '), ('age', '24'), ('sex ',' male ')) # increase newId = input("Please enter your id") info['id'] = newId print("_"*20) # Print split lines print('Traverse dictionary elements after adding') for i in info: print(i,info[i]) # Delete # del del info['id'] # Delete the corresponding value according to the key print("Traversal dictionary element after deletion") for i in info: print(i,info[i]) del info; # Delete dictionary # clear: clears all elements in the dictionary info.clear(info); # change info['name'] = 'wjw' for i in info: print(i,info[i]) # ergodic # Traverse all primary keys for i in info.keys(): print(i) # Traverse all values for i in info.values(): print(i) # Traverse all key values for key,value in info.items(): print(key,value)
Note: supplementary knowledge
myList = ['a','b','c','d','e','f'] for i,x in enumerate(myList): # Use the enumeration function to obtain the subscript index and the element corresponding to the subscript in the list at the same time print(i+1,x)
5.set
1. Set definition
Set is a set of key s, but does not store value
- Create an empty collection
myset = set()
- Define a collection
myset = set([1,2,3]) print(type(myset)) #Output result: < class' set '> print(myset) # Output result: {1, 2, 3}
2. Characteristics of set
- A set of key s, but no value is stored
- key cannot be repeated
- set is unordered, and duplicate elements are automatically filtered
3. Common methods
method | Operation name | Explain operation |
for i in myset:print(i) | Traversal set | Traverse the elements in the collection through the for loop |
myset.update(set1) | Update collection | Appends elements from other collections to the current collection |
myset.add(key) | Add element | Adds an element to the current collection |
myset.remove(key) | Delete element | Remove the existing elements in the current collection. If the key does not exist, an error will be reported |
val = myset.pop() | Pop up element | Randomly pop up an element in the current collection, and val represents the popped element |
myset.clear() | Clear element | Clears all elements of the current collection |
del myset | Delete collection | Delete entire collection |
len() | length | Get collection length |
max() | Maximum | Gets the largest element in the collection |
min() | minimum value | Gets the smallest element of the collection |
set() | transformation | Convert objects of other types to collections |
myset = set([1,2,3]) print(type(myset)) print(myset) #increase set1 = set(['qzp','wjw']) myset.update(set1) print(myset) myset.add('wangze') print(myset) # Delete myset.remove('wangze') print(myset) val = myset.pop() print(val) print(myset) print(myset.clear()) del myset
6. Summary
data type | Is it orderly | Variable type |
List [] | Orderly | Variable type |
Tuple () | Orderly | Immutable type |
Dictionary {} | disorder | key is immutable and value is variable |
Set {} | disorder | Variable type (no repetition) |