## Life is short, I learn Python

osc_ fhqvuif4 2021-01-20 12:38:18
life short learn python

Hello everyone ！ I am a 【AI bacteria 】, I'm lucky to be in this 【 Blog star 】 General selection , Please cast a key vote for me , You can choose the maximum number of votes , Thank you very much ！1 month 25 recently , There are votes every day ~

-> Go to 【 Life is too short , I learned Python】 General catalogue <-

## One 、 List Introduction

### (1) What is a list

A list consists of a series of elements arranged in a specific order . These elements can be ： Numbers 、 Letter 、 Strings and other types of data . stay Python in , In square brackets `[ ]` To represent a list , And use commas to separate the elements . Here's a simple example of a list ：

``````Week_list = ["Monday", "Tuseday", "Wednseday", "Thursday",
"Friday", "Saturday", "Sunday"]
print(week_list)
``````

If you use print() function , Python The internal representation of the list will be printed , Include brackets ：

``````['Monday', 'Tuseday', 'Wednseday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
``````

If you want to output every element in the list directly , Then you have to learn how to access the elements of the list .

### (2) Access list elements

A list is an ordered set , So to access any element of the list , Just know where the element is in the list . To access list elements , You can indicate the name of the list , And then point out the index of the element , And put it in square brackets . for example , We want to get the Friday：

``````Week_list = ["Monday", "Tuseday", "Wednseday", "Thursday",
"Friday", "Saturday", "Sunday"]
print(Week_list[4])
``````

The above demonstrates the syntax for accessing list elements . When you ask for a list element , Python Returns only the value of the element , It doesn't include square brackets and quotation marks ：

``````Friday
``````

Of course , If you want to output each element in the list in turn , Can pass for Realization ：

``````Week_list = ["Monday", "Tuseday", "Wednseday", "Thursday",
"Friday", "Saturday", "Sunday"]
for day in Week_list:
print(day)
``````

adopt for Loop through the list , Output each element in turn ：

``````Monday
Tuseday
Wednseday
Thursday
Friday
Saturday
Sunday
``````

### (3) Nested list

Nested lists create other lists in the list , for example ：

``````list1 = [1, 2, 3]
list2 = [" Cao Cao ", " king of Wu in the Three Kingdoms Era ", " Liu bei "]
list = [list1, list2]
print(list)
``````

Nested list means that the elements in the list are lists ：

``````[[1, 2, 3], [' Cao Cao ', ' king of Wu in the Three Kingdoms Era ', ' Liu bei ']]
``````

When you want to take an element in the list , such as “ Cao Cao ”, You need to learn how to use the index .

## Two 、 Indexes 、 Slicing and list copying

### (1) Indexes

The index value depends on the position of the element . stay Python in , The index of the first list element is 0 , instead of 1 . According to this simple way of counting , To access any element of the list , Can be reduced to 1 , And index the results . for example , To visit the 10 List elements , You can use the index 9.

For normal lists , When we want to visit its second 5 Element time ：

``````Week_list = ["Monday", "Tuseday", "Wednseday", "Thursday",
"Friday", "Saturday", "Sunday"]
print(Week_list[4])
``````

Program input ：

``````Friday
``````

For nested lists , When we want to access the elements , Like in the list above “ Cao Cao ”, In the following way ：

``````list = [[1, 2, 3], [' Cao Cao ', ' king of Wu in the Three Kingdoms Era ', ' Liu bei ']]
print(list[1][0])
``````

Program input ：

`````` Cao Cao
``````

among ,list[1][0] Index value in 1 Take the second list , Index value 0 It means to take the first element in the second list .

### (2) section

The index provides access to a single list element , By slicing, you can handle the list of All or part of the elements . To create slices , You can specify the index of the first and last element to be used . The main thing is ：Python Stop after reaching the element before the second index you specify .

1. for example ： To output the first three elements in the list , Need to specify index 0~3 , This will output 0 、 1 and 2 The elements of .

``````Week_list = ["Monday", "Tuseday", "Wednseday", "Thursday", "Friday", "Saturday", "Sunday"]
print(Week_list[0:3])
``````

Slice the first three elements of the list ：

``````['Monday', 'Tuseday', 'Wednseday']
``````

2. You can also get any subset of the list , for example , If you want to extract the first 2~6 Elements , The starting index can be specified as 1 , And specify the termination index as 6 ：

``````Week_list = ["Monday", "Tuseday", "Wednseday", "Thursday", "Friday", "Saturday", "Sunday"]
print(Week_list[1:6])
``````

Output Tuesday to Saturday ：

``````['Tuseday', 'Wednseday', 'Thursday', 'Friday', 'Saturday']
``````

3. If the first index is not specified , Python Will automatically start at the beginning of the list ：

``````Week_list = ["Monday", "Tuseday", "Wednseday", "Thursday", "Friday", "Saturday", "Sunday"]
print(Week_list[:6])
``````

Output Monday to Saturday ：

``````['Monday', 'Tuseday', 'Wednseday', 'Thursday', 'Friday', 'Saturday']
``````

4. If you want to take the second 3 Elements to all elements at the end of the list , It can also be done in the following ways ：

``````Week_list = ["Monday", "Tuseday", "Wednseday", "Thursday", "Friday", "Saturday", "Sunday"]
print(Week_list[2:])
``````

Go back to Wednesday to Sunday ：

``````['Wednseday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
``````

5. If you want to traverse parts of the list , Then you can for Use slices in the loop .

``````Week_list = ["Monday", "Tuseday", "Wednseday", "Thursday", "Friday", "Saturday", "Sunday"]
for day in Week_list[:3]:
print(day)
``````

Traverse the list 1 to 3 Elements , And the output ：

``````Monday
Tuseday
Wednseday
``````

### (3) Copy list

In the development process , We often need to create new lists based on existing lists . Let's talk about Copy list How it works , And a situation where copying lists can be of great help .

To copy a list , You can create a slice that contains the entire list , The method is to omit both the starting index and the ending index `[ : ]` . This makes Python Creating one starts with the first element , A slice that ends at the last element , Copy the entire list .

``````Week_list = ["Monday", "Tuseday", "Wednseday", "Thursday", "Friday", "Saturday", "Sunday"]
Week_list_copy1 = Week_list
Week_list_copy2 = Week_list[:]
print("Week_list:", id(Week_list))
print("Week_list_copy1:", id(Week_list_copy1))
print("Week_list_copy2:", id(Week_list_copy2))
``````

We use and don't use `[ : ]` Two ways to copy , Get the list of id as follows ：

``````Week_list: 298963473096
Week_list_copy1: 298963473096
Week_list_copy2: 298963418440
``````

It can be seen from the results ：Week_list_copy1 Same as original list Week_list Of id identical , explain Week_list_copy1 And the original list points to the same list ;Week_list_copy2 Same as original list Week_list Of id Different , Explain through `[ : ]` The way to copy , What you create is a new list .

## 3、 ... and 、 Number of list elements 、 Maximum 、 minimum value 、 transformation

stay Python in , Contains some built-in functions , It's easy to handle data like lists .

### (1) Number of return elements

For normal lists , Returns the number of list elements ：

``````Week_list = ["Monday", "Tuseday", "Wednseday", "Thursday",
"Friday", "Saturday", "Sunday"]
print(len(Week_list))
``````

Program output ：

``````7
``````

For nested lists , Returns the number of lists in the list ：

``````list = [[1, 2, 3], [' Cao Cao ', ' king of Wu in the Three Kingdoms Era ', ' Liu bei ']]
print(len(list))
``````

Program output ：

``````2
``````

### (2) Returns the maximum value of the element

max() Method returns the maximum value in the list element ：

``````list1, list2 = ['Google', 'Baidu', 'Taobao'], [1, 2, 3]
print("list1 Maximum element value : ", max(list1))
print("list2 Maximum element value : ", max(list2))
``````

The maximum value of the elements in the output list ：

``````list1  Maximum element value : Taobao
list2  Maximum element value : 3
``````

### (3) Returns the minimum value of the element

min() Method returns the minimum value in the list element ：

``````list1, list2 = ['Google', 'Baidu', 'Taobao'], [1, 2, 3]
print("list1 Minimum element value : ", min(list1))
print("list2 Minimum element value : ", min(list2))
``````

The minimum value of the element in the output list ：

``````list1  Minimum element value : Baidu
list2  Minimum element value : 1
``````

### (4) Converts a tuple to a list

list() Method to convert a tuple or string to a list ：

``````str = "Hello Python"
list2 = list(str)
print(" List elements : ", list2)
Tuple = (123, 'Google', 'baidu', 'Taobao')
list1 = list(Tuple)
print(" List elements : ", list1)
``````

The result of the procedure ：

`````` List elements : ['H', 'e', 'l', 'l', 'o', ' ', 'P', 'y', 't', 'h', 'o', 'n']
List elements : [123, 'Google', 'baidu', 'Taobao']
``````

notes ： Tuples are very similar to lists , The difference is that the element value of a tuple cannot be modified , Tuples are in parentheses , The list is in square brackets .

## Four 、 modify 、 Add and delete operations

### (1) Modify list elements

The syntax for modifying list elements is similar to that for accessing list elements . To modify a list element , You can specify the list name and the index of the element to be modified , Then specify the new value of the element . For example, below , We'll take the first value in the list ：

``````Week_list = ["Monday", "Tuseday", "Wednseday", "Thursday",
"Friday", "Saturday", "Sunday"]
Week_list[0] = " Monday "
print(Week_list)
``````

Put... In the list Monday Change it to “ Monday ”：

``````[' Monday ', 'Tuseday', 'Wednseday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
``````

Of course , You can modify the values of any list element , Not just the value of the first element .

### (2) Add elements at the end of the list

When you add a new element to the list , The easiest way is to use append() Add elements to the end of the list ：

``````Week_list = ["Monday", "Tuseday", "Wednseday", "Thursday",
"Friday", "Saturday", "Sunday"]
Week_list.append(100)
print(Week_list)
``````

take 100 Add to the end of the list ：

``````['Monday', 'Tuseday', 'Wednseday', 'Thursday', 'Friday', 'Saturday', 'Sunday', 100]
``````

Use append() It's easy to create lists , for example , You can create an empty list first , Use a series of append() Statement to add elements . Let's create an empty list , Add elements to it ：

``````Week_list = []
Week_list.append(1)
Week_list.append(2)
Week_list.append(3)
print(Week_list)
``````

Program output ：

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

### (3) Insert elements in the list

Usage method insert() You can add new elements anywhere in the list . So , You need to specify the index and value of the new element ：

``````Week_list = ["Monday", "Tuseday", "Wednseday", "Thursday",
"Friday", "Saturday", "Sunday"]
Week_list.insert(0, 100)
print(Week_list)
``````

Add... At the beginning of the list 100：

``````[100, 'Monday', 'Tuseday', 'Wednseday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
``````

### (4) Delete list elements

In data processing , We often need to remove one or more elements from the list .Python Provides 4 To delete elements from a list ：

1. Use del Statement delete element . If you know where the element to delete is in the list , You can use del sentence .

``````Week_list = ["Monday", "Tuseday", "Wednseday", "Thursday", "Friday", "Saturday", "Sunday"]
del Week_list[0]
print(Week_list)
``````

Delete the first element in the list ：

``````['Tuseday', 'Wednseday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
``````

2. Usage method pop() Remove elements . Method pop() You can delete the elements at the end of the list , And allow you to continue to use it .

``````Week_list = ["Monday", "Tuseday", "Wednseday", "Thursday", "Friday", "Saturday", "Sunday"]
Week_list.pop()
print(Week_list)
``````

Delete the last element in the list ：

``````['Monday', 'Tuseday', 'Wednseday', 'Thursday', 'Friday', 'Saturday']
``````

3. Delete elements anywhere in the list . actually , Use pop() You can also delete elements anywhere in the list , Just specify the index of the element to be deleted in brackets .

``````Week_list = ["Monday", "Tuseday", "Wednseday", "Thursday", "Friday", "Saturday", "Sunday"]
Week_list.pop(1)
print(Week_list)
``````

Delete the second element in the list ：

``````['Monday', 'Wednseday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
``````

notes ： If you're not sure you should use del Statement or pop() Method , Here's a simple criterion ： If you want to remove an element from the list , And no longer use it in any way , Just use del sentence ; If you're going to be able to use it after deleting the element , Just use the method pop() .

4. Delete elements... Based on values . occasionally , You don't know where the value to delete from the list is . If you only know the value of the element to be deleted , Serviceable method remove() .

``````Week_list = ["Monday", "Tuseday", "Wednseday", "Thursday", "Friday", "Saturday", "Sunday"]
Week_list.remove("Monday")
print(Week_list)
``````

Delete the elements in the list "Monday"：

``````['Tuseday', 'Wednseday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
``````

notes ：remove() What is deleted is the first match of a value in the list

## 5、 ... and 、 List operators

### (1) Splicing operators

stay Python,`+` It can also be used as a splice operator , Put different lists together into one list ：

``````list1 = [1, 2, 3]
list2 = [4, 5, 6]
print(list1 + list2)
``````

Put together a list ：

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

### (2) Copy operator

Use `*` The operator , You can easily copy list elements ：

``````list = [1, 2, 3]
print(list * 2)
``````

Copy all the elements in the list to 2 times ：

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

In the same way , It can be replicated many times .

## 6、 ... and 、 Sort the list

In the actual development process , Sometimes you want to keep the list elements in their original order , And sometimes you need to adjust the order . Python There are many ways to organize lists , You can choose according to the specific situation .

### (1) Permanent sort sort()

sort() It makes it easier for you to sort the list , The elements in the list are sorted alphabetically ：

``````Week_list = ["Monday", "Tuseday", "Wednseday", "Thursday", "Friday", "Saturday", "Sunday"]
Week_list.sort()
print(Week_list)
``````

adopt sort() Sort , Is to permanently change the order of elements in the original list ：

``````['Friday', 'Monday', 'Saturday', 'Sunday', 'Thursday', 'Tuseday', 'Wednseday']
``````

When sorting in descending order , Just to sort() Method pass parameter reverse=True, As shown below ：

``````Week_list = ["Monday", "Tuseday", "Wednseday", "Thursday", "Friday", "Saturday", "Sunday"]
Week_list.sort(reverse=True)
print(Week_list)
``````

The descending sort result is as follows ：

``````['Wednseday', 'Tuseday', 'Thursday', 'Sunday', 'Saturday', 'Monday', 'Friday']
``````

### (2) Temporary sorting sorted()

Sometimes I want to sort the list , If necessary, keep the order of the elements in the original list , You can use sorted() function .

``````Week_list = ["Monday", "Tuseday", "Wednseday", "Thursday", "Friday", "Saturday", "Sunday"]
Week_list_sorted = sorted(Week_list)
print(Week_list_sorted)
print(Week_list)
``````

Compare the sorted results ：

``````['Friday', 'Monday', 'Saturday', 'Sunday', 'Thursday', 'Tuseday', 'Wednseday']
['Monday', 'Tuseday', 'Wednseday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
``````

It can be seen that ：sorted() It doesn't change the order of the elements in the original list .

## 7、 ... and 、 Other member functions

### (1) Count the number of times an element appears count()

count() Method is used to count the number of times an element appears in the list . such as ：

``````list = [1, 2, 2, 2, 3]
print(" In the list 2 The number of ：", list.count(2))
``````

Running results ：

`````` In the list 2 The number of ： 3
``````

### (2) Find the index position of the first match of a value in the list index()

index() Function to find the index position of the first match of a value from the list . For example, find out 2 The index of ：

``````list = [1, 2, 2, 2, 3]
print(" In the list 2 First occurrence index ：", list.index(2))
``````

Running results ：

`````` In the list 2 First occurrence index ： 1
``````

in addition , You can also specify a location in the list to start searching ：

``````list = [1, 2, 2, 2, 3, 2, 3]
print(" Starting with the fifth element , In the list 2 First occurrence index ：", list.index(2, 4))
``````

From index value to 4 Start searching for , The result is ：

`````` Starting with the fifth element , In the list 2 First occurrence index ： 5
``````

### (3) Reverse list of elements reverse()

reverse() Function is used to reverse the list of elements . When we want to reverse the list of elements ：

``````Week_list = ["Monday", "Tuseday", "Wednseday", "Thursday", "Friday", "Saturday", "Sunday"]
Week_list.reverse()
print(Week_list)
``````

After reversing the position of the elements in the list , The output is ：

``````['Sunday', 'Saturday', 'Friday', 'Thursday', 'Wednseday', 'Tuseday', 'Monday']
``````

### (4) clear list clear()

clear() Function to clear the list , Be similar to del a[:].

``````Week_list = ["Monday", "Tuseday", "Wednseday", "Thursday", "Friday", "Saturday", "Sunday"]
Week_list.clear()
print (" After the list is cleared : ", Week_list)
``````

After the list is cleared ：

`````` After the list is cleared : []
``````

### (5) Copy list copy()

copy() Function for Copy list , Similar to the index mentioned above [:] The way it's copied .

``````Week_list = ["Monday", "Tuseday", "Wednseday", "Thursday", "Friday", "Saturday", "Sunday"]
Week_list_copy1 = Week_list.copy()
print("Week_list:", id(Week_list))
print("Week_list_copy():", id(Week_list_copy1))
``````

Running results ：

``````Week_list: 250643256008
Week_list_copy(): 250643201352
``````

It can be seen that ： Use copy() The way to copy a function is the same as passing through [:] It's copied in a similar way , They all create a new list .

-> go back to 【 Life is too short , I learned Python】 General catalogue <-

Due to limited level , There are some mistakes in blogs , If there is any mistake, please give me your advice ！

https://pythonmana.com/2021/01/20210120121905385h.html