List of Python getting started

1. Create:

Create a list s1 s1=[1,2,3,,4,'hui','ggg','aaa'] 

Create empty list s2 s2=[]

 

2. Inquiry

name=["shan","gaohui","aaa","bbb",1,2,5,6,7,5,9,3]

1) If you query from the front, the index starts from 0

Example: Find shan: name[0]

2) If you query from the back, the index starts from -1

Example: Find 3: name[-1]

3) Check the index value

Example: Find the index value of aaa: name.index(aaa) #If there are multiple aaa, only the index value of the first aaa will be displayed.

4) Check the number in the list

Example: Find how many aaa are in the list: name.count(aaa)

 

3. Slicing method: don't care about the end

name=["shan","gaohui","aaa","bbb",1,2,5,6,7,5,9,3]

1) Output the first 4:

print(name[0:4]) 输出为:"shan","gaohui","aaa","bbb"   

2) Output the last 5:

The output of print(name[-5:]) is: [6,7,5,9,3] ##The last 0 can be omitted, so the first 4 of the above output can also be written as name[:4]

3) Output the first 4 bits and output one bit in the interval:

The output of print(name[0:4:2]) is: ["shanshan", "aaa"] #If every 2 bits is output, the colon after 4 is 3 (this 3 is called the step size)

 

 

4. Add and Append

name=["shan","gaohui","aaa","bbb",1,2,5,6,7,5,9,3]

1) Add content xxx at the end

name.append(“xxx”)

2) Add a "ccc" before aaa

name.insert(2(index),"ccc) The position to insert is one position before this index

 

5. Modification

name=["shan","gaohui","aaa","bbb",1,2,5,6,7,5,9,3]

1) Change "aaa" to "ccc"

name[2]="ccc"

2) Change "aaa" and "bbb" to "Jack Liu"

name[2:4]="Jack Liu" The output is: ['shanshan', 'gaohui', 'J', 'a', 'c', 'k', ' ', 'L', 'i', 'u', 1, 2, 5, 6, 7, 5, 9, 3]

 

6. Delete

1) name.pop(): delete the last one in the list

2) name.remove("content in the list") ##If there are multiple defaults, delete the first one

3) del name[2] ##Index in brackets del name[index:index]

 

 

7. Loop

for i in [] #list or for i in range[0,10]

Difference between for and while loop:

for cannot be defined as an infinite loop while can be defined as an infinite loop

 

 

8. Sort

name=["shan","gaohui","aaa","bbb",1,2,5,6,7,5,9,3]

name.sort() sort by ascll code

n.reverse() reverse

 

9. Splicing

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

name2=[1,2,4,5,6]

Method 1: name+name2

Method 2: name=name.extend(name2)

 

 

 

 

              

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324816587&siteId=291194637