[Python self study] summary of knowledge points

Most of the content comes from "zero basic Python from getting started to mastering" and network query. I hope I can also give some help to other small partners. If there are errors, please correct them.

Chapter I to II

It mainly introduces the overview and installation of python, which is omitted here

Chapter III small test Python

1. Figures

Python's number types are mainly divided into integer int, floating point float, complex, fixed-point decimal, fractional fraction, etc

be careful:

'/'  The division operator returns a floating point number
>>>7/2
3.5
'//'integer division operator returns an integer
>>>7//2
3
'**'  Exponential operator
>>>2**4
16

Use = = to compare whether the values are equal (regardless of type); Use = = = comparison to compare types and whether values are equal

All numeric types (except complex numbers) support the following operations

Sort in ascending order of priority 2. String

The string is enclosed in '' (single quotation mark) or '' (double quotation mark)

Use \ (backslash) to escape special characters

>>> print("C:\windows\name")
C:\windows
ame
>>> print(r"C:\windows\name")
C:\windows\name

Here, the \ n on the path is escaped. You can add r before the string quotation marks

'' content '' (three single quotes) or '' content '' (three double quotes) to represent a multiline string

The end of each line will be automatically added with a newline character, or \ can be added to avoid outputting a newline character

print("""
How are you?
I'm fine.""")

O:

How are you?
I'm fine.

print("""\
How are you?
I'm fine.""")

O:
How are you?
I'm fine.

Strings can be connected by + and repeated by * with two or more adjacent strings, which will be merged automatically at the end

Access the position of a character in the string by index (if it is negative, it is from right to left, - 0 and 0 represent the first character, and the reverse order is calculated from - 1 in the following table)

Use of index:

>>> word = 'Python'
>>> word[-1]
'n'

Use of slices:

>>> word = 'Python'
>>> word[0:2]
'Py'

word[a:b] starts from a and ends at B (excluding b). If a is omitted, it starts from 0 by default. If omitted, it ends at the end by default

Working principle of slicing: regard the index as the point between characters, the leftmost boundary is 0, the rightmost of n characters is n, and take the characters between the two boundaries

+---+---+---+---+---+---+
| P | y | t | h | o | n |
+---+---+---+---+---+---+
0   1   2   3   4   5   6
-6  -5  -4  -3  -2  -1

Slicing does not change the original string

Simple string function

word = "Hello World"
print("implement replace front:" + word)
print("word The number of characters is" + str(len(word)))
word = word.replace("World","Python")
print("implement replace after:" + word)

O:
implement replace front:Hello World
word The number of characters is 11
implement replace after:Hello Python

Len (string name) returns the number of strings

replace(a,b,[c]) replaces string a with string b, [c] as an optional parameter, indicating the maximum number of replacements

3. Boolean type

There are only two values: True and False

4. Literal and constant

Literal quantity is literal variable. Naming rules: variable name consists of characters, numbers_ Composition, cannot start with a number

Constants cannot change the value of constants. Python syntax does not define constants, but most languages often use all uppercase variable names to represent constants

The Convention is not to change the name of the variable in all uppercase

5. Expression

Expression can be understood as "anything with value"

name=language='Python'

This is a line, but there are two expressions

The assignment order of expressions is from right to left. Generally, only one expression is written in one line (high readability)

So the above statements can be divided into

language='Python'
name=language

6. Notes

Single line comment with #: the content within # a line will not be run as code (usually written at the beginning or the first line)

Multiline comments use three single or double quotation marks

'''
Use three single quotes as the beginning and end of the comment
You can annotate multiple lines of content at once
The contents in it are all notes
'''

"""
Use three double quotes as the beginning and end of the comment
You can annotate multiple lines of content at once
The contents in it are all notes
"""

Keywords in and is

In determines whether it is included in the specified sequence

is determines whether two identifiers refer to the same object

>>> 5 in (1,2,5,8,10)
True

>>> a = 20
>>> b = 20
>>> a is b
True

Chapter IV data structure

Most python sequences can perform general operations, including index, slice, addition of sequences of the same type, multiplication, membership, length, maximum and minimum

1. Sequence

There are three basic sequence types (they are all sequences):

List:	[1,2,3,4]
Tuple:	(1,2,3,4)
character string:"1234" or '1234'

Index syntax: variable name [element number]

From left to right 0~n-1

From right to left -1~-n (the rightmost is - 1)

Slice syntax: variable name [a:b:c] a is the start position (0 by default) and b is the end position (the last bit by default)

c is an optional parameter, indicating the step size (the default is 1, 0 is not supported, and negative numbers are taken from right to left)

[ValueError: slice step cannot be zero]

Step size is positive: the start point must be less than the end point; step size is negative: the start point must be greater than the end point

x1 = [1,2,3,4,5]
print(x1[1:4])
print(x1[1:4:2])

O:
[2, 3, 4]
[2, 4]

Sequence operation demonstration

#Sequence addition (the same sequence type shall be connected with '+' number)
x1 = [0,1,2,3]+[4,5,6]
print("List:",x1)
x2 = "Hello "+"World!"
print("character string",x2)

O:
List: [0, 1, 2, 3, 4, 5, 6]
character string Hello World!

x1 = *5
print("list:: ",x1)
x2 = "Go!"*3
print("character string:",x2)
x3 = *0
print("list:: ",x3)
x4 = "Go!"*0
print("character string:",x4)

O:
list::  [2233, 2233, 2233, 2233, 2233]
character string: Go! Go! Go!
list::  []
character string:

#Membership (judge whether the element is in the sequence) A in B judge whether the A on the left is in the B on the right, and only if the element type and value are exactly the same can it be regarded as including '= ='
x1 = [0,1,2,3]
print("list:",0 in x1)
print("list:",8 in x1)
x2 = "Hello World123"
print("character string:","Hello" in x2)
print("character string:","good o" in x2)
#Error: 	 print(123 in x2)

O:
list: True
list: False
character string: True
character string: False
#Error: 	 TypeError: 'in <string>' requires string as left operand, not int
#123 is an int and "123" is a string

#Length, minimum value, maximum value, sum (len and sum can only accept one sequence, strings are connected with '+', and strings are compared with ASCII code)
x1 = [0,1,2,3]
print("list x1:",x1)
print("List length:",len(x1))
print("List maximum:",max(x1))
print("List minimum:",min(x1))
print("List summation:",sum(x1))

x1 = [0,1,2,3]
x2 = [7,8,9]
print("list x1:",x1,"  x2:",x2)
print("Maximum value of two lists:",max(x1,x2))
print("Minimum value of two lists:",min(x1,x2))

x3 = "Hello word!"
print("character string x1:"+x3)
print("String length:",len(x3))
print("String maximum:",max(x3))
print("String minimum:",min(x3))

x3 = "Hello word!"
x4 = "Hello China!"
print("character string x3:"+x3+"  x4:"+x4)
print("Maximum value of two strings:",max(x3,x4))
print("Minimum value of two strings:",min(x3,x4))

O:
list x1: [0, 1, 2, 3]
List length: 4
List maximum: 3
List minimum: 0
List summation: 6
list x1: [0, 1, 2, 3]   x2: [7, 8, 9]
Maximum value of two lists: [7, 8, 9]
Minimum value of two tables: [0, 1, 2, 3]
character string x1:Hello word!
String length: 11
String maximum: w
String minimum:
character string x3:Hello word!  x4:Hello China!
Maximum value of two strings: Hello word!
Minimum value of two strings: Hello China!

2. List

The list can store different types of data, and the contents can be obtained or updated through the index, and the front and rear types can be inconsistent

x1 = [0,1,"Hello",[2,3]]
print(x1)
x1 = "world"
print(x1)

O:
[2, 3]
world

Append (element) function

#3 is an element of type int
x1 = [0,1,2]
x1.append(3)
print(x1)

O:
[0, 1, 2, 3]

# Is an element of type list with only one data
x1 = [0,1,2]
x1.append()
print(x1)

O:
[0, 1, 2, ]

#[3,4] is a list of element types
x1 = [0,1,2]
x1.append([3,4])
print(x1)

O:
[0, 1, 2, [3, 4]]

Extend (list) function

Add multiple elements A.extend(B) later, that is, add the data of List B to the back of list a

# Is a list
x1 = [0,1,2]
x1.extend()
print(x1)

O:
[0, 1, 2, 3]

#[3,4] is a list
x1 = [0,1,2]
x1.extend([3,4])
print(x1)

O:
[0, 1, 2, 3, 4]

#[, ] is a list consisting of two lists
x1 = [0,1,2]
x1.extend([,])
print(x1)

O:
[0, 1, 2, , ]

Insert (index, element) function

Insert (one) element anywhere

x1 = [0,1,2]
x1.insert(0,9)
print(x1)

O:
[9, 0, 1, 2]

#Exceeding the index value will be added to the last digit
x1 = [0,1,2]
x1.insert(10,9)
print(x1)

#The index value is a negative number (the absolute value does not exceed the index value), which is placed at the (input) index value plus one position from right to left
x1 = [0,1,2]
x1.insert(-1,9)
print(x1)

O:
[0, 1, 9, 2]

#A negative number with an index value of (absolute value exceeds the index value) is the same as an index value of plus or minus zero, and is placed first
x1 = [0,1,2]
x1.insert(-10,9)
print(x1)

O:
[9, 0, 1, 2]

x1 = [0,1,2]
x1.insert(-0,9)
print(x1)

O:
[9, 0, 1, 2]
2.2) delete element

Pop (index) function

Delete an element in the list according to the index (the default is the last) and take the element as the return value

x1 = [4,5,2,1]
print(x1.pop())
print(x1)

O:
1
[4, 5, 2]

x1 = [4,5,2,1]
print(x1.pop(1))
print(x1)

O:
5
[4, 2, 1]

Remove (element) function

Receive an element (the element must exist, otherwise an error will be reported). Deleting the element according to the content will only delete the first element found, and there is no return value

x1 = [5,6,7,8]
print(x1.remove(6))
print(x1)

O:
None
[5, 7, 8]

#When the content in remove does not exist in the list
#ValueError: list.remove(x): x not in list

del keyword

Specify the list element and index after del

x1 = [0,4,5,6]
del x1
print(x1)

O:
[0, 4, 6]
2.3) other operations
1. Reverse can reverse the list, which is similar to [:: - 1], but reverse modifies the original list and has no return value
x1 = [0,1,2,3]
print(x1.reverse())
print(x1)

O:
None
[3, 2, 1, 0]
1. count counts the number of times an element appears in the list
x1 = [0,1,2,2,2,3]
print(x1.count(2))

O:
3
1. Sort sorts the list. You can customize the sorting method. Sort will modify and sort the source list without return value
x1 = [3,4,1,5,6,2]
x1.sort()
print(x1)

O:
[1, 2, 3, 4, 5, 6]

3. Tuple

Tuples are similar to lists, but tuples cannot be modified or deleted after they are created. A single element can be deleted as a whole

Because tuples cannot be modified, queries are faster

3.1) defining tuples

type(A) can judge the type of A

#The comma after the last element can be added or not, but only one element must be added
x1 = (1,2,3)
x2 = (0,)
print(type(x1))
print(type(x2))

O:
<class 'tuple'>
<class 'tuple'>

3.2) delete tuples

del keyword

x1 = (1,2,3)
del x1
print(x1)

O:
NameError: name 'x1' is not defined
3.3) other operations
1. count counts the number of occurrences of an element in a tuple

2. index finds the position of an element in a tuple

x1 = (1,"hello","world")
print(x1,"index is ",x1.index("hello"))

O:
hello index is  1

4. Dictionary

Dictionary types can be found like dictionaries (such as Array in PHP and HashMap in Java)

Key value correspondence (key:value)

1 Definition Dictionary
dog = {
"name":"kk",
"color":"white",
"action":"run",
}

print(type(dog))
print(dog)

O:
<class 'dict'>
{'name': 'kk', 'color': 'white', 'action': 'run'}

#Define an empty dictionary
empty = {}
print(type(empty))
print(empty)

O:
<class 'dict'>
{}
2) Use dictionary

A dictionary is a set of key value pairs that use keys to access values

dog = {
"name":"kk",
"color":"white",
"action":"run",
}

print(dog["name"],"is ",dog["color"])

O:
kk is  white

dog = {
"name":"kk",
"color":"white",
"action":"run",
}

dog["name"] = "aa"
print(dog["name"],"is ",dog["color"])

O:
aa is  white

The syntax of adding elements is the same as that of modifying elements

dog = {
"name":"kk",
"color":"white",
"action":"run",
}

dog["animal"] = "dog"
print(dog)

O:
{'name': 'kk', 'color': 'white', 'action': 'run', 'animal': 'dog'}

Delete use del keyword

dog = {
"name":"kk",
"color":"white",
"action":"run",
}

dog["animal"] = "dog"
del dog["action"]
print(dog)
del dog
print(dog)

O:
{'name': 'kk', 'color': 'white', 'animal': 'dog'}
NameError: name 'dog' is not defined
3) Other operations
1. clear() clear dictionary

dog = {
"name":"kk",
"color":"white",
"action":"run",
}
dog.clear()
print(dog)

O:
{}

2. copy() returns the same new dictionary (copy a new copy)

dog = {
"name":"kk",
"color":"white",
"action":"run",
"animal":"dog",
}
cat = dog
qwq = dog.copy()
print("Original value")
print("dog:",dog)
print("cat:",cat)
print("qwq:",qwq)

print("change")
cat["animal"] = "cat"
qwq["qwq"] = "Coding"
print("dog:",dog)
print("cat:",cat)
print("qwq:",qwq)

#Direct assignment is similar to sharing an address. Changes will affect other values, and copy is a new independent dictionary
O:
Original value
dog: {'name': 'kk', 'color': 'white', 'action': 'run', 'animal': 'dog'}
cat: {'name': 'kk', 'color': 'white', 'action': 'run', 'animal': 'dog'}
qwq: {'name': 'kk', 'color': 'white', 'action': 'run', 'animal': 'dog'}
change
dog: {'name': 'kk', 'color': 'white', 'action': 'run', 'animal': 'cat'}
cat: {'name': 'kk', 'color': 'white', 'action': 'run', 'animal': 'cat'}
qwq: {'name': 'kk', 'color': 'white', 'action': 'run', 'animal': 'dog', 'qwq': 'Coding'}

1. fromkeys() creates a new dictionary, using the elements in the sequence as keys, and the second parameter is the initial value corresponding to all parameters
x1 = ["name","age","class"]
x2 = ["kk",15,0]
print("Default:",dict.fromkeys(x1))
print("Not default:",dict.fromkeys(x1,x2))

O:
Default: {'name': None, 'age': None, 'class': None}
Not default: {'name': ['kk', 15, 0], 'age': ['kk', 15, 0], 'class': ['kk', 15, 0]}

3. get() returns the value corresponding to the key. If it does not exist, it returns the default value (accessed with the key value. If it does not exist, an error will be reported)

dog = {
"name":"kk",
"color":"white",
"action":"run",
"animal":"dog",
}
print("name:",dog.get("name"))
print("age:",dog.get("age"))
print("age:",dog.get("age",15))

O:
name: kk
age: None
age: 15
1. keys() returns a list of all the keys in the dictionary. It is often used with in to determine whether a key is in the dictionary
dog = {
"name":"kk",
"color":"white",
"action":"run",
"animal":"dog",
}
key = dog.keys()
print(key)
print("name" in key)
print("age" in key)

O:
dict_keys(['name', 'color', 'action', 'animal'])
True
False
1. values() returns a list of all values
dog = {
"name":"kk",
"color":"white",
"action":"run",
"animal":"dog",
}
print(dog.values())

O:
dict_values(['kk', 'white', 'run', 'dog'])
1. items() returns a list containing all key values (the actual type is < class' dict_items'). Because the dictionary cannot be traversed directly, itmes often traverses the dictionary with keys and values
dog = {
"name":"kk",
"color":"white",
"action":"run",
"animal":"dog",
}
key = dog.keys()
value = dog.values()
print(dog.items())
for key,value in dog.items():
print(key,"=>",value)

O:
dict_items([('name', 'kk'), ('color', 'white'), ('action', 'run'), ('animal', 'dog')])
name => kk
color => white
action => run
animal => dog

5. Assemble

A collection is like a list, but it does not contain duplicate values

1. Define set
empty = set()       #If {} is directly assigned, it will be an empty dictionary. The set function must be used to define an empty set
print(type(empty))

empty_dict = {}     #Empty dictionary
print(type(empty_dict))

x1 = {1,2,3,}       #Braces plus elements, the last comma can be added or not
print(type(x1))

x2 = set([1,"Hello",0.1])   #Set (list)
print(type(x2))

O:
<class 'set'>
<class 'dict'>
<class 'set'>
<class 'set'>

#Filter duplicate elements
x3 = {1,2,2,2,2}
print(x3)

O:
{1, 2}

When adding a new element using the add() function (only one parameter is accepted), if it exists, it will not be added to ensure the uniqueness of the set element

x1 = {1,2,3}
print(x1)
print(x1)

O:
{1, 2, 3, 4}
{1, 2, 3, 4}

Remove available

x1 = {1,2,3,4}
x1.remove(4)
print(x1)

O:
{1, 2, 3}

6. Derivation

1) List derivation

Syntax: enclosed in square brackets, use the for statement in the middle, followed by the if statement for judgment, and those that meet the conditions will be transferred to the for statement, followed by the list for construction

x1 = [0,1,2,3,4,5,6]
x2 = [x for x in x1 if x%2 == 0 ]
print(x2)

O:
[0, 2, 4, 6]

List derivation is best at doing the same operation on the whole list and returning to get a new list

2) Dictionary derivation

Similar to list derivation. Value pairs are generated in pairs when the derivation is defined

x1 = {x:x**2 for x in range(5)}
print(x1)

x2 = {v:k for k,v in x1.items()}
print(x2)

x3 = {k:v**0.5 for k,v in x1.items()}
print(x3)

O:
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
{0: 0, 1: 1, 4: 2, 9: 3, 16: 4}
{0: 0.0, 1: 1.0, 2: 2.0, 3: 3.0, 4: 4.0}
3) Set derivation

It is the same as the list derivation, but the duplicate elements are removed and curly braces are used

x1 = {x**2 for x in range(5)}
print(x1)
x2 = {x for x in x1 if x%2 == 1}
print(x2)

O:
{0, 1, 4, 9, 16}
{1, 9}

To ensure the uniqueness of collection elements

x1 = {1,2,3}
print(x1)
print(x1)

O:
{1, 2, 3, 4}
{1, 2, 3, 4}

Remove available

x1 = {1,2,3,4}
x1.remove(4)
print(x1)

O:
{1, 2, 3}

6. Derivation

1) List derivation

Syntax: enclosed in square brackets, use the for statement in the middle, followed by the if statement for judgment, and those that meet the conditions will be transferred to the for statement, followed by the list for construction

x1 = [0,1,2,3,4,5,6]
x2 = [x for x in x1 if x%2 == 0 ]
print(x2)

O:
[0, 2, 4, 6]

List derivation is best at doing the same operation on the whole list and returning to get a new list

2) Dictionary derivation

Similar to list derivation. Value pairs are generated in pairs when the derivation is defined

x1 = {x:x**2 for x in range(5)}
print(x1)

x2 = {v:k for k,v in x1.items()}
print(x2)

x3 = {k:v**0.5 for k,v in x1.items()}
print(x3)

O:
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
{0: 0, 1: 1, 4: 2, 9: 3, 16: 4}
{0: 0.0, 1: 1.0, 2: 2.0, 3: 3.0, 4: 4.0}
3) Set derivation

It is the same as the list derivation, but the duplicate elements are removed and curly braces are used

x1 = {x**2 for x in range(5)}
print(x1)
x2 = {x for x in x1 if x%2 == 1}
print(x2)

O:
{0, 1, 4, 9, 16}
{1, 9}

Keywords: Python

Added by hebisr on Wed, 05 Jan 2022 02:46:15 +0200