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 ~

Voting channels :

 Insert picture description here

-> 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"]

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"]

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 :


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:

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


(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]

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"]

Program input :


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 ']]

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"]

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"]

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"]

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"]

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]:

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


(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"]

Program output :


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 ']]

Program output :


(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 "

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"]

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 = []

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)

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]

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"]

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"]

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"]

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"]

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"]

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)

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"]

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"]
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 <-
 Insert picture description here
Due to limited level , There are some mistakes in blogs , If there is any mistake, please give me your advice !

本文为[osc_ fhqvuif4]所创,转载请带上原文链接,感谢

  1. 利用Python爬虫获取招聘网站职位信息
  2. Using Python crawler to obtain job information of recruitment website
  3. Several highly rated Python libraries arrow, jsonpath, psutil and tenacity are recommended
  4. Python装饰器
  5. Python实现LDAP认证
  6. Python decorator
  7. Implementing LDAP authentication with Python
  8. Vscode configures Python development environment!
  9. In Python, how dare you say you can't log module? ️
  10. 我收藏的有关Python的电子书和资料
  11. python 中 lambda的一些tips
  12. python中字典的一些tips
  13. python 用生成器生成斐波那契数列
  14. python脚本转pyc踩了个坑。。。
  15. My collection of e-books and materials about Python
  16. Some tips of lambda in Python
  17. Some tips of dictionary in Python
  18. Using Python generator to generate Fibonacci sequence
  19. The conversion of Python script to PyC stepped on a pit...
  20. Python游戏开发,pygame模块,Python实现扫雷小游戏
  21. Python game development, pyGame module, python implementation of minesweeping games
  22. Python实用工具,email模块,Python实现邮件远程控制自己电脑
  23. Python utility, email module, python realizes mail remote control of its own computer
  24. 毫无头绪的自学Python,你可能连门槛都摸不到!【最佳学习路线】
  25. Python读取二进制文件代码方法解析
  26. Python字典的实现原理
  27. Without a clue, you may not even touch the threshold【 Best learning route]
  28. Parsing method of Python reading binary file code
  29. Implementation principle of Python dictionary
  30. You must know the function of pandas to parse JSON data - JSON_ normalize()
  31. Python实用案例,私人定制,Python自动化生成爱豆专属2021日历
  32. Python practical case, private customization, python automatic generation of Adu exclusive 2021 calendar
  33. 《Python实例》震惊了,用Python这么简单实现了聊天系统的脏话,广告检测
  34. "Python instance" was shocked and realized the dirty words and advertisement detection of the chat system in Python
  35. Convolutional neural network processing sequence for Python deep learning
  36. Python data structure and algorithm (1) -- enum type enum
  37. 超全大厂算法岗百问百答(推荐系统/机器学习/深度学习/C++/Spark/python)
  38. 【Python进阶】你真的明白NumPy中的ndarray吗?
  39. All questions and answers for algorithm posts of super large factories (recommended system / machine learning / deep learning / C + + / spark / Python)
  40. [advanced Python] do you really understand ndarray in numpy?
  41. 【Python进阶】Python进阶专栏栏主自述:不忘初心,砥砺前行
  42. [advanced Python] Python advanced column main readme: never forget the original intention and forge ahead
  43. python垃圾回收和缓存管理
  44. java调用Python程序
  45. java调用Python程序
  46. Python常用函数有哪些?Python基础入门课程
  47. Python garbage collection and cache management
  48. Java calling Python program
  49. Java calling Python program
  50. What functions are commonly used in Python? Introduction to Python Basics
  51. Python basic knowledge
  52. Anaconda5.2 安装 Python 库(MySQLdb)的方法
  53. Python实现对脑电数据情绪分析
  54. Anaconda 5.2 method of installing Python Library (mysqldb)
  55. Python implements emotion analysis of EEG data
  56. Master some advanced usage of Python in 30 seconds, which makes others envy it
  57. python爬取百度图片并对图片做一系列处理
  58. Python crawls Baidu pictures and does a series of processing on them
  59. python链接mysql数据库
  60. Python link MySQL database