Python common usage two

1. Update the list

#coding:utf8
 
x1 = [1,2,3,4,5,6,7]
列表更新
x1 [2] ="hello"吧  

2. Add elements:

Use the append method to append a new element at the end of the list, but note that append can only add one element at a time. If you want to add multiple elements, you must use the extend method

x1.append("hello")
print(x1)
x1.append([6,7])
print(x1)

 extend method:

x1.extend([6,7])

3. Insert an element in the middle of the list

x1.inset(2,"hello")

The insert method passes two parameters, the first parameter indicates the position of the new element to be inserted, and the second parameter indicates the new element to be inserted. Insert can only add one element at a time

4, delete element
   pop function is used to remove an element in the list (the default is the last element), and return the value of the element.

#coding:utf8
 
x1 = [1,2,3,4,5,6,7]
print(x1)
r1 = x1.pop()
print(r1)
print(x1)
print("...................")
x2 = [1,2,3,4,5,6,7]
print(x2)
r2 = x2.pop(2)
print(r2)
print(x2)

operation result: 

Not only can elements be deleted according to their position, but also elements can be deleted according to their content. The remove method provides such a function

  

#coding:utf8
 
x1 = ["hello","google","baidu"]
print(x1)
x1.remove("hello")
print(x1)

operation result:

 

You can also use the keyword "del" to delete list elements

5. Find the element

Python provides the index method to find the index position of the element in the list

#coding:utf8
 
x1 = ["hello","google","baidu"]
print("baidu index is",x1.index("baidu"))

operation result:

6, Reverse the queue

The reverse method has no return value

#coding:utf8
 
x1 = [1,2,3,4,5,6,7]
print(x1)
x1.reverse()
print(x1)

operation result:

7, the count method is used to count the number of times an element appears in the list

 

#coding:utf8
 
x1 = ["hello","google","baidu","hello","baidu","hello"]
print(x1)
print(x1.count("hello"))
print(x1.count("baidu"))

operation result:

8. The sort method is used to sort the list, you can also customize the sorting method, and there is no return value

# coding:utf8

x1 = [1, 2, 3, 4, 5, 6, 7]
print(x1)
x1.sort()
print(x1)
print(type(x1))

operation result:

 

Guess you like

Origin blog.csdn.net/wzhrsh/article/details/106536211