python learning records - List

Posted by fr34k2oo4 on Sat, 01 Jan 2022 15:31:42 +0100

list

1. What list
A list is a collection used to store different data.

2. Create a list
Wrap all the elements to be placed in the list, separated by commas.

[1,2,3,4,5]
[1,2,3,4,5,'ukd']

The above two are lists, but they are not named, so they cannot be called. We can name the list like this.

i = [1,2,3,4,5,'ukd']
print(i)

output:

Like this, we can call and output this list.

3. Access and output the elements in each class table in order

i = [1,2,3,4,5,'ukd']
for j in i:
    print(j)

Using the for loop, you can output the elements in each list in order.
output:

But you can't just output a specific list element. So you can introduce subscripts to the list.

The subscript of the first element is 0,
The subscript of the second element is 1,
The subscript of the third element is 2,
and so on

You can also use subscripts like this:

The last element subscript is-1
 The penultimate element is shown in the following table-2
 and so on

Like this:

i = [1,2,3,4,5,'ukd']
print(i[0],i[-1])

ouput:

1 ukd

You can also use the len() function to measure the length of the list

i = [1,2,3,4,5,'ukd']
length = len(i)
print(length)

output:

4. List slice:

i = [1,2,3,4,5,'ukd']
print(i[1:4])
print(i[:4])
print(i[:])
print(i[::2])    

output:

[2, 3, 4]
[1, 2, 3, 4]
[1, 2, 3, 4, 5, 'ukd']
[1, 3, 5]

This is the slicing use of the list.
First:

List name[start:stop]

The output starts from the element whose subscript is start and stops at the position whose subscript is stop.

Second:

List name[:stop]

If you don't give the value of start, the output starts from the first element by default and stops at the position with the subscript stop.

Third:

List name[:]

If start and stop are not assigned, all elements in the list will be output by default.

Fourth:

List name[start:stop:step]

Here, start and stop can also be empty, and step is responsible for the step frequency, that is, the span value output from the list. So when print(i[::2]) is output, the result is [1, 3, 5].

Use of lists

1, Add, delete, modify and query

1. Increase

Is to add elements to the original list
a.append() method
The function of append is to add a specified element to the end of the list.
Add format:

List name.append('Added element')

For example, chestnuts:

i = [1,2,3]
i.append(4)
print(i)

output:

[1, 2, 3, 4]

The disadvantage of the append() method is that only one element can be added at the end of the list, which is no longer applicable when multiple elements need to be added at one time.

b.extend() method

You can add any element at the end of the list. Note: the parameter of the extend() method must be an iteratable object.

Format:

List name.extend([Element 1,Element 2,...])

For example, chestnuts:

i = [1,2,3]
i.extend([4,5,6])
print(i)

output:

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

c. Use slices to complete the addition

Format:

List name[len(List name):] = [Element 1,Element 2,...]

For example, chestnuts:

i = [1,2]
i[len(i):] = [3]
print(i)

output:

[1, 2, 3]

Another example:

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

d.insert() method

Format:

List name.inset(Subscript of the position to be inserted,Element to be inserted)

Take a chestnut;

i = [1,3,4]
i.insert(1,2)
print(i)
i.insert(len(i),5)
print(i)

output:

[1, 2, 3, 4]
[1, 2, 3, 4, 5]

2. Delete

a.remove() method

Format;

List name.remove('Delete element')

Take a chestnut;

i = [1,2,2,3]
j = [1,2,3,4]
i.remove(2)
j.remove(4)
print(i)
print(j)

output:

[1, 2, 3]
[1, 2, 3]

matters needing attention:
1. If there are multiple matching elements in the list, only the first one will be deleted. For example, list i in the example.
2. If there is no matching element in the list, an error will be reported.

b.pop() method

Format;

List name.pop(Element subscript)

For example, chestnuts:

i = [1,2,3,4]
i.pop(0)
print(i)

output:

[2, 3, 4]

c.clear() method
Format:

List name.clear()

For example, chestnuts:

i = [1,2,3,4]
i.clear()
print(i)

output:

[]

The entire method will directly empty all elements in the list.

3. Change

a. Subscript index method
In essence, the change operation of the list is to use the subscript index method to replace the new element value with the assignment operator.

For example, chestnuts:

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

output;

[1, 2, 3, 4]

This method can only change one element.

b. Slice method
The principle of this method is to delete the content of the specified location first, and then insert the new element to be corrected into the original specified location.
Format;

List name[start:stop] = [New element]

Take a chestnut;

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

out[put:

[1, 2, 3, 4]

This slicing method is very easy to use. Practice more.

expansion

Sort a disorderly list of numbers from small to large.
You can use a module in python.
sort() can achieve the above functions.
Format:

List name.sort()

For example, chestnuts:

i = [1,4,5,8,4]
print(i)
i.sort()
print(i)

output:

[1, 4, 5, 8, 4]
[1, 4, 4, 5, 8]

To sort from large to small, you need to use the reverse() module
Format:

List name.reverse()

Chestnuts:

output:

4. Check

a.count() method

This method is used to find the number of an element in its list.
Format:

List name.count(Element 1)

Chestnuts:

output;

b.index() method
This method is used to find the index value (subscript) of an element
Format:

List name.index(Element 1,start,stop)

Chestnuts:

output:

be careful:
When start and stop are not assigned, and the searched element is more than one in its list, the index value of the first occurrence will be returned. For example, index(4) in chestnuts will only return the location where it first appears, that is, where the index value is 1.

With the index method, combined with the subscript index method in the modification operation, it can be modified even if the index value of the content to be modified is not known.
Chestnuts:

output:

When we copy start and stop, we can find the latter one even if there are multiple identical elements.
Chestnuts:

output:

You can see that although the elements to be searched are all 4, the results are different because the index in the second print defines the assignment of start.

2, Copy of list (shallow copy)
1. Slicing method
Format:

List to be assigned = Copied list[start:stop:step]

Chestnuts:

output:

2.copy() method
Format:

List to be assigned = Copied list.copy()

Chestnuts:

output:

This method can only be copied completely, and its flexibility is not as flexible as the slicing method.

Concatenation and multiplication of list

1, Addition of lists
The addition of lists is actually the splicing of lists, so it is required that there are lists on both sides of the symbol.
Format:

List name 1 + List name 2

Chestnuts:

output:

2, Multiplication of lists
In fact, it is to repeat the elements in the list n times
Chestnuts:

output:

nested list

1, Nested list

Nested lists can also be called binary lists. For example, matrix = [[1,2],[3,4]] is a two-dimensional list.
Or write this:

matrix = [[1,2],
          [3,4]]

The second way is more intuitive.

Expansion:
We can use the multiplication of the list to create a two-dimensional list. such as

A = [0]*3
for i in range(3):
	A[i] = [0] *3

The list created in this way looks like this, [[0, 0, 0], [0, 0, 0], [0, 0, 0]. However, it should not be created in this way for convenience:

B = [[0]*3]*3

Although the list created in this way is also [[0, 0, 0], [0, 0, 0], [0, 0, 0]]. But problems arise when we need to change elements in a certain location.
For example, if we need to rectify B[1][1] in List B, this will happen:

output:

You can see that all values in B [i] [1] (I < 3) have been changed. This is a list created directly by multiplication. When stored, all B [i] (I < 3) are the same object.

output:

This explains why you can't use multiplication directly to create lists.
Finally, a picture is attached to understand:

This is how A and B are stored.

2, access nested list
First:
Subscript access method

matrix = [[1,2],
              [3,4]]
for i in range(2):
    for j in range(2):
        print(matrix[i][j],end = ' ')
    print( )

output:

Second:
section:

matrix = [[1,2],
              [3,4]]
for i in matrix:
    for j in i:
        print(j,end = ' ')
    print( )

output:

Deep copy

Variable is not a box
In python, a variable is a name, not a box. Specifically, when assigning a value to a variable, it is actually a reference. For example, chestnuts:

In this example, when the assignment operation occurs, python does not put the data into the variable, but refers to (hook the variable to the data), which is like this:

We can find that if we modify the value in X, such as x[1] = 3, the value in y will also change. If you want to get two independent lists, you need to use the copy() method or the slicing method, which are shallow copies.

Deep copy
In the replication of the list, the shallow copy is enough, but when facing the copy of the two-dimensional list, the shallow copy is not enough to meet the requirements, so the deep copy is introduced
Format:

import copy//Call module
 List name to be copied = copy.deepcopy(Copied list name)

Chestnuts:

output:

After deep copy, you can have two independent two-dimensional lists.
In a two-dimensional list, this would be the case if you used a shallow copy instead of a deep copy.

output;

List derivation expression

Problem introduction:
If you need to multiply each value in a list of numbers by 2, how do you do it.
Of course, it can be implemented in the form of for loop and subscript index:


Like this, it's OK, but it's not brief enough, so the list derivation is introduced:

Like this, it can also solve problems and be more concise.

Format l;

[expression for target in iterable]

Chestnuts;

output:

This list derivation is equivalent to the in the for loop;

x = []
for i in range(10):
	x.append(i)

Use of derivation in string;

ouytput:

Use of list derivation

1. With if judgment
Format:

[expression for target in interable if condition]

Chestnuts:

output:

The internal execution order of the derivation is: first execute the for statement, then execute the if judgment, and finally the expression part.
2. Nesting of derivation
Format:

[expression for target1 in iterable1
			for target2 in iterable2
			...
			for targetN in iterableN]

Chestnut: reduce the dimension of a two-dimensional list to a one-dimensional list

output:

Derivation execution sequence:

1.for j in x  
2.for i in j
3.i

It is essentially the nesting of loops.
At the same time: judgment conditions can also be added to the nesting of derivation:
Format:

[expression for target1 in iterable1 if condition1
			for target2 in iterable2 if condition2
			...
			for targetN in iterableN if conditionN]

Chestnuts:

This will produce a two-dimensional array, which is the Cartesian product of odd and even numbers within 10:

Topics: Python Back-end