Python learning notes 2021-10-13

Posted by frigidman on Wed, 13 Oct 2021 03:06:25 +0200

What is a container and what is a list

In life, a container refers to a container that can hold items. In a program, a container is a data structure that can put multiple elements together. The elements in the container can be obtained iteratively one by one. You can use keywords such as in, not in to judge whether an element is contained in the container.
In Python, including list, tuple, dict, set, etc., they can be put into multiple elements, so they can be regarded as containers. These containers are very important data structures in Python programming. We will focus on learning these data structures next.

A list is an ordered container. The elements in the list will be arranged in a certain order. The method of constructing a list is very simple. You define a list by enclosing the elements that need to be placed in the container with square brackets [].
For example, list the achievements of all students:

scores = [45, 60, 75, 86, 49, 100]

List the names of all students:

names = ['Alice', 'Bob', 'David', 'Ellena'] # Note that quotation marks are still required for string elements

As we can see, list can put numbers, strings and other data types. List does not judge the types put in it, that is, list can put any type of data at the same time, which is determined by python, because Python is a dynamic language.

L = ['Alice', 66, 'Bob', True, 'False', 100]

For the list, we can print the contents of the list directly.

L = ['Alice', 66, 'Bob', True, 'False', 100]
print(L)

Alice's scores in Chinese, math and English were 92, 75 and 99 respectively. Please use list to save these data.

L = ['Alice', 'Chinese', 92, 'Math', 75, 'English', 99]
print(L)
```.
## Python accesses the list sequentially
 The list is ordered, so we can access the elements in the list in order.

```python
L = ['Alice', 66, 'Bob', True, 'False', 100]
for item in L:
    print(item)

Recall that we learned about strings earlier. It is very similar to using the for loop to access each element in the list and using the for loop to access each character in the string.
In fact, a string can also be regarded as a special list, which can only store multiple characters in order. The way to access each element of the list through a for loop is called iteration.
For an empty list, using the for loop access, nothing will be printed.

L = []
for item in L:
    print(item)

Please use the iterative method to output the elements at even positions of list L = ['Alice', 66, 'Bob', True, 'False', 100] in order.

num = 0
L = ['Alice', 66, 'Bob', True, 'False', 100]
for item in L:
    num = num + 1
    if num % 2 != 0:
        continue
    print(item)

Python accesses the list by index

Because the list is an ordered container, each element in the list has a unique position, which is called index, which is similar to the string. Therefore, we can also obtain the elements in the list by position. Review the previous learning, we access the corresponding elements by position through brackets [].
Note that the definition of the list is also defined by brackets [], but this does not conflict with accessing the elements in the list through the index

names = ['Alice', 'Bob', 'David', 'Ellena']
print(names[0])
print(names[1])
print(names[2])
print(names[3])

Since names has only four elements, we can only access the last element through index 3 at most. Imagine if we print(names[4])?

names = ['Alice', 'Bob', 'David', 'Ellena']
print(names[4])

In fact, this will cause an error in Python running, prompting that the index access is out of range.

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: list index out of range

Therefore, when we use the index to access the list, we must pay special attention not to cross the boundary.
At the same time, lists, like strings, also support slicing. Through slicing, you can obtain the sub lists of the list.

names = ['Alice', 'Bob', 'David', 'Ellena']
sub_names = names[0:2]
print(sub_names)

It should be noted here that if we slice beyond the boundary, there will be no Python running error, but if we slice according to this subscript, we can't get any elements.

names = ['Alice', 'Bob', 'David', 'Ellena']
sub_names = names[5:10]
print(sub_names) # ==> []

Python access list in reverse order

Python's list supports not only the forward order index to obtain each element in the list, but also the reverse order access to each element in the list.

names = ['Alice', 'Bob', 'David', 'Ellena']

For the names list, Ellena's name comes last, which is what we call the penultimate. In Python, you can use - 1 to represent the last element.

names = ['Alice', 'Bob', 'David', 'Ellena']
print(names[-1]) # ==> Ellena

Similarly, we can print out David's name through - 2 and Bob's position through - 3.

print(names[-2]) # ==> David
print(names[-3]) # ==> Bob

Note that if we use - 5, because there is no penultimate name, it is also an out of bounds and will also report an error.

names = ['Alice', 'Bob', 'David', 'Ellena']
print(names[-5])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: list index out of range

Python adds a new element to the list

Now there are four students in the class:

names = ['Alice', 'Bob', 'David', 'Ellena']

Today, a new classmate Candy came to the class. How to add the new classmate to the existing list?
In Python, list provides a series of methods that allow us to manipulate the elements in the list, including the method of adding elements.
The first method is to use the append() method to append the new student to the end of the list:

names = ['Alice', 'Bob', 'David', 'Ellena']
names.append('Candy')
print(names) # ==> ['Alice', 'Bob', 'David', 'Ellena', 'Candy']

Note that the append() method always adds elements to the end of the list.
If the above list needs to be sorted alphabetically, Candy should be in the third place. What should I do?
This requires the use of the insert() method of the list. The insert() method is different from the append() method. The insert() method requires two parameters, namely, the position to be inserted and the element to be inserted.

names = ['Alice', 'Bob', 'David', 'Ellena']
names.insert(2, 'Candy')
print(names) # ==> ['Alice', 'Bob', 'Candy', 'David', 'Ellena']

Note that after inserting Candy into the third position, the original name will automatically move back one bit. At this time, if you use the same index to obtain the following elements, you will get different results

names = ['Alice', 'Bob', 'David', 'Ellena']
print(names[2]) # ==> David
names.insert(2, 'Candy')
print(names[2]) # ==>Candy

Python deletes an element from a list

If Ellena needs to transfer for family reasons, how can we delete Ellena from the existing list?
At this time, we can use the pop() method of the list. The pop() method deletes the last element of the list by default and returns.

L = ['Alice', 'Bob', 'Candy', 'David', 'Ellena']
name = L.pop()
print(name) # ==> Ellena
print(L) # ==> L = ['Alice', 'Bob', 'Candy', 'David']

For Ellena, because Ellena is at the end of the list, you can directly use the pop() method to delete Ellena from the end of the list. What should you do if it is not Ellena but Candy who needs to transfer?
pop() method, in addition to deleting the last element, pop() can also receive a parameter to specify the location of the element to be deleted.

L = ['Alice', 'Bob', 'Candy', 'David', 'Ellena']
name = L.pop(2)
print(name) # ==> Candy
print(L) # ==> ['Alice', 'Bob', 'David', 'Ellena']

Python replaces the elements in the list
For the list, in addition to adding elements to the list and deleting list elements, the existing elements in the list can also be modified. The original elements in the list can be replaced by indexing the specified position and assigning a new element.
If the classmate Candy needs to be transferred, and a new classmate cannina needs to be transferred, then in alphabetical order, cannina's position happens to be Candy's position.

L = ['Alice', 'Bob', 'Candy', 'David', 'Ellena']
L[2] = 'Canlina'
print(L)

We can also use reverse index to accomplish the same function.

L = ['Alice', 'Bob', 'Candy', 'David', 'Ellena']
L[-3] = 'Canlina'
print(L)

Note that replacing a nonexistent subscript will also cause Python running errors.

L = ['Alice', 'Bob', 'Candy', 'David', 'Ellena']
L[6] = 'Canlina'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: list assignment index out of range

Python 2D list

Sometimes, one-dimensional lists cannot meet all requirements (all the above lists are one-dimensional lists). At this time, two-dimensional lists or even higher dimensional lists are required.
For example:
Alice's last three scores are [100, 89, 92]
Bob's last three achievements are [70, 65, 81]
Candy's last three achievements are [88, 72, 77]
If you need to use a list to store the scores of three students, you need to do the following:

alice_scores = [100, 89, 92]
bob_scores = [70, 65, 81]
candy_scores = [88, 72, 77]
all_scores = [alice_scores, bob_scores, candy_scores]
print(all_scores) # ==> [[100, 89, 92], [70, 65, 81], [88, 72, 77]]

At this time, you get a two-dimensional list. For a two-dimensional list, each element in the list is still a list. At this time, if you need to start from the 2D list all_scores get Bob's score in the third recent exam. You can write this as follows

alice_scores = [100,89,92]
bob_scores = [70,65,81]
candy_scores = [88,72,77]
all_scores = [alice_scores, bob_scores, candy_scores]
score = all_scores[1][2] # ==> 81

Where all_ Score [1] gets the list of Bob's last three scores, and then through the subscript [2], you can get Bob's third score

Topics: Python Pycharm data structure