Python basic syntax

catalogue

1. Notes

2. Variables and types

3. Keyword (identifier)

1. What are keywords?

2. View keywords

3. Keywords

4. Format output

5. Input

6. Judge variable name type

7. Operator

8. Process control statement  

1. Conditional judgment statement

if branch statement:

If else double branch statement:

Multi branch if elif else statement:

if nesting:

2. Circular statement

for loop

while Loop

Syntax format:

While else loop

practice:

9.break, continue and pass statements

  10. Escape character

  11.import and from... import

  Exercise:

12. Core data types of Python

1. String

1. String format

2. String method

2.List

1. Definition of list

2. Precautions for list:  

3. Common methods of list

4. List nesting

5. Application exercise:

3.Tuple (tuple)

1. Definition of tuple

2. Tuple access

  3. Common methods of tuples

4.dict (Dictionary)

1. Definition of dictionary

2. Characteristics of dictionary

3. Access to dictionaries  

4. Common methods of dictionary

5.set

1. Set definition

2. Characteristics of set

3. Common methods

6. Summary

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 symbolConversion meaning
%ccharacter
%sFormat through str() string conversion
%iSigned decimal integer
%dSigned decimal integer
%uUnsigned decimal integer
%oOctal integer
%xHexadecimal integer (lowercase)
%XHexadecimal integer (uppercase letter)
%eIndex symbol (lowercase e)
%EIndex symbol (capital E)
%fFloating 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 characterdescribe
\Backslash symbol
'Single quotation mark
"Double quotation mark
\aRing the bell
\bBackspace
\000empty
\vVertical tab
\thorizontal tab
\renter
\fPage change
\oyyOctal number, yy represents the character, for example: \ o12 represents line feed, where o is a letter, not a number 0
\xyyHexadecimal number, yy represents the character, for example: \ x0a represents line feed
\otherOther 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 numbermethod         describe         
1capitalize()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
4bytes.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'
6endswith(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
7expandtabs(tabsize=8)Turn the tab symbol in the string into a space. The default number of spaces for the tab symbol is 8
8find(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
9index(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
10isalnum()Returns True if the string has at least one character and all characters are letters or numbers, otherwise returns False
11isalpha()Returns True if the string has at least one character and all characters are letters, otherwise returns False
12isdigit()Returns True if the string contains only numbers; otherwise, returns False
13islower()Returns True if the string contains at least one case sensitive character and all of these (case sensitive) characters are lowercase; otherwise, returns False
14isnumeric()Returns True if the string contains only numeric characters, otherwise False
15isspace()Returns True if the string contains only white space; otherwise, returns False
16istitle()Returns True if the string is captioned (see title()), otherwise returns False
17isupper()Returns True if the string contains at least one case sensitive character and all of these (case sensitive) characters are uppercase; otherwise, returns False
18join(seq)Use the specified string as the separator to merge all elements (string representation) in seq into a new string
19len(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.
21lower()Converts all uppercase characters in a string to lowercase
22lstrip()Truncate the space to the left of the string or the specified character
23ITmaketrans()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.
24max(str)Returns the largest letter in the string str
25min(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
27rfind(str,beg=0,end=len(string))It is similar to the find() function, but it starts from the right
28rindex( 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
30rstrip()Delete spaces at the end of the string
31split(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
33startswith(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
35swapcase()Converts uppercase to lowercase and lowercase to uppercase in a string
36title()Returns a "captioned" string, that is, all words start with uppercase and the rest are lowercase (see istitle())
37translate(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
38upper()Converts lowercase letters in a string to uppercase
39zfill (width)Returns a string with a length of width. The original string is right aligned and filled with 0
40isdecimal()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

methodOperation name

Explain operation

list[index]Accessing elements in a listDirect access to elements in the list through Subscripts
list[start​: end: length​]Slice of listUse [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 elementsfor loop
list.append(values)[add] append data to the end of the listAppends the new element value to the end of the current list
list.extend(list1)Add listAdds elements from other lists to the current list
list.insert(index,value)[add] list data insertionInserts an element at a specified location based on the given index
del list[index]
list.remove(value)
Delete: delete the listdel: 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 listPop 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 listModify the specified element by subscript
value in list
value not in list
[query] list membershipin
not in
list.index(value,start,end)[query] list membershipFind 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 elementsCounts the number of occurrences of the specified element in the current list
list3 = list1 +list2Addition operation of list+
list.sort()Sort listSorts the current list elements
list.reverse()Inversion of [row] listInverts all elements of the list
len()Get list lengthGets the current list length
max()Gets the maximum value of the list elementGets the maximum value of the list element
min()Gets the minimum value of the list elementGets the minimum value of the list element
list()Convert other types of objects to listsConvert 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

methodOperation nameExplain operation
tuple[index]Accessing elements in tuplesAccessing elements in tuples through Subscripts
for i in tuple:print(i)Traversal tuplefor loop
tuple[start: end: length]Slice of tuplesUse [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 membershipin not in
tuple.count(value)[query] find the number of occurrences of elementsCounts the number of occurrences of the specified element in the current tuple
tuple3 = tuple1+tuple2Addition operation of tuplesNew method of tuple
len()Get tuple lengthGet tuple list length
max()Gets the maximum value of the tuple elementGets the maximum value of the tuple element
min()Gets the minimum value of the tuple elementGets the minimum value of the tuple element
tuple()Convert objects of other types to tuplesConvert 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

methodOperation nameInterpretation method
dict[key]Accessing elements in a dictionaryIf the key does not exist, an exception will be thrown
dict.get(key)Accessing elements in a dictionaryThrough the get method, None is returned and no exception is thrown
for key in dict: print(key,dict[key])Traversal dictionaryThrough 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 dictionaryUse 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] = newvalueModify valueModify value directly through key
dict[newkey] = newvalueNew key value pairDirect addition
del dict[key]Delete dictionary elementDelete dictionary elements through key
dict.pop(key)Pop up dictionary elementPop up dictionary elements through key
key in dictDetermine whether the key existsin
dict.update(dict2)Merge dictionary
dict(zip(list1,list2))Convert a list into a dictionaryTurn two lists into dictionaries   
dict2 = dict([['key1','value1']])Turn a nested list into a dictionaryTurn a nested list into a dictionary
dict.clear()Clear elements in dictionaryClear 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

methodOperation nameExplain operation
for i in myset:print(i)Traversal setTraverse the elements in the collection through the for loop
myset.update(set1)Update collectionAppends elements from other collections to the current collection
myset.add(key)Add elementAdds an element to the current collection
myset.remove(key)Delete elementRemove the existing elements in the current collection. If the key does not exist, an error will be reported
val = myset.pop()Pop up elementRandomly pop up an element in the current collection, and val represents the popped element
myset.clear()Clear elementClears all elements of the current collection
del mysetDelete collectionDelete entire collection
len()lengthGet collection length
max()MaximumGets the largest element in the collection
min()minimum valueGets the smallest element of the collection
set()transformationConvert 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 typeIs it orderlyVariable type
List []OrderlyVariable type
Tuple ()OrderlyImmutable type
Dictionary {}disorderkey is immutable and value is variable
Set {}disorderVariable type (no repetition)

Tags: Python Algorithm

Posted on Tue, 05 Oct 2021 15:06:50 -0400 by kaoskorruption