Maybe like most ordinary people , I went through a special 2020 year . At sea , Getting sleepy , Straighten out self-cultivation .
finally 2021 In the spring of the recovery of all things , I stood myself up , Start learning and recording again . The first step is to organize or review systematically Python. I used to study intermittently because of my work , All the knowledge you know is scattered , Writing code is patchwork .
I hope this review can get a complete picture .
list Is the container data type （collection） One of them , It allows multiple values to be stored in a variable .
list Can store any Python data type , for example number,string,character, Even list.
list =  #empty list list = [1, 2, 3, 4] list = ['a', 'b', 'c', 'd'] list = ["apple", "banana", "cat", "dog"] list = [1, [2, 3], 4]
And string similar ,list You can also use indexing obtain list A value in , Such as ：
list = [1, 2, 3, 4] print(list) >> 3
But and string The difference is , list The value of is modifiable , and string The value of is not modifiable .
list = ['a', 'p', 'p', 'l', 'e'] list = 'x' print(list) >> ['a', 'p', 'x', 'l', 'e']
To connect or divide list, There are two important symbols , Namely “+” and “：”.
“+” It's used to connect two list, Such as ：
a = [1, 2] b = [3, 4] list = a + b print(list) >> [1, 2, 3, 4]
“：” It's for segmentation list Of , Such as ：
list = [1, 2, 3, 4, 5] sublist = list[1:3] #from index = 1 to index = 3-1 print(sublist) >> [2, 3] sublist = list[:3] #from index = 0 to index = 3-1 print(sublist) >> [1, 2, 3] sublist = list[1:] #from index = 1 to index = len(list) -1 print(sublist) >> [2, 3, 4, 5]
List a few commonly used methods.
- append： Add a new value
- in： Check list Whether to include a value
list = [1, 2, 3, 4] print(9 in list) >> False
- sort： Yes list Sort by
- len： Calculation list The length of
- max,min,sum： Calculation list The maximum of , Minimum and sum
List and Loop
If you need to traverse list Each value in is also simple , We can use for：
list = [1, 2, 3, 4, 5] for ii in list: print(ii)
You can also use for and range() Traverse list Medium index, To obtain list Value :
list = [1, 2, 3, 4, 5] for ii in range(len(list)): print(list[ii])