除了append()與extend()方法外,List中常用的方法還有如下幾個:
1、count()方法
用於統計某個元素在列表中出現的次數
語法:list.count(obj)
obj--列表中統計的對象
List = ['haha', 'yaya', 'lala', 'haha']
print(List.count('haha'))
2、index()方法
用於從列表中找出某個值第一個匹配項的索引位置(從左至右查找),返回查找對象的索引位置,如果沒有找到對象則拋出異常。
語法:list.index(x[, start[x,end]])
x-- 查找的對象。
start-- 可選,查找的起始位置。
end-- 可選,查找的結束位置。
3、insert()方法
用於將指定對象插入列表的指定位置
語法:list.insert(index, obj)
index -- 對象obj需要插入的索引位置
obj -- 要插入列表中的對象
insert()方法與append()、extend()方法區別:
(1)insert()方法可以插入指定的任意位置,append()和extend()方法只能在列表末尾插入
(2)insert()方法是將序列如列表、元組、字典當做一個新的元素插入,extend()方法是將一個序列中的所有元素依次在原列表尾部插入
4、pop()方法
用於移除列表中的一個元素(默認最后一個元素),並且返回該元素的值
語法:list.pop(index) index是索引值,默認為-1 即刪除最后一個元素
List = ['haha', 'yaya', 'lala', 'haha']
Tuple = ('heihei', 'aa')
List2 = ['www', '2323']
Dict1 = {"Name": "lele", "Age": "18"}
List.insert(1, Tuple)
List.insert(2, List2)
List.insert(2, Dict1)
print(List.pop())
print(List.pop(-2))
print(List)
5、remove()方法
用於移除列表中某個值的第一個匹配項。
語法:list.remove(obj) obj--列表中要移除的對象
List = ['haha', 'yaya', 'lala', 'haha']
Tuple = ('heihei', 'aa')
List2 = ['www', '2323']
Dict1 = {"Name": "lele", "Age": "18"}
List.insert(1, Tuple)
List.insert(2, List2)
List.insert(2, Dict1)
print(List)
List.remove('haha')
print(List)
pop()與remove()的區別
(1)pop是刪除指定索引位置的元素,是根據索引刪除,remove是根據要刪除的對象從左至右進行查找,刪除第一個匹配的元素
6、reverse()方法
用於將列表中的元素反向排序
語法:list.reverse()
List = ['haha', 'yaya', 'lala', 'haha']
Tuple = ('heihei', 'aa')
List2 = ['www', '2323']
Dict1 = {"Name": "lele", "Age": "18"}
List.insert(1, Tuple)
List.insert(2, List2)
List.insert(2, Dict1)
print(List)
List.reverse()
print(List)
7、sort()方法
用於對列表進行排序,如果指定參數,則使用比較函數指定的比較函數
語法:list.sort(key=None ,reverse=False)
key -- 主要是用來進行比較的元素,只有一個參數,具體的函數的參數就是取自於可迭代對象中,指定可迭代對象中的一個元素來進行排序。(沒有使用過,暫不理解)
reverse -- 排序規則,reverse=True 降序 ,reverse=False 升序 默認是升序
List_new = ['haha', 'aiai', '我家']
List_new.sort()
print(List_new)
List_new.sort(reverse=True)
print(List_new)
注意:不同數據類型之間不能進行比較排序,如str和int不能一起比較排序,str、int和tuple、list、dict不能一起比較排序,list不能和其他非list類型比較排序,運行會報錯
8、clear()方法
用戶清空列表
語法:list.clear()
List = ['haha', 'yaya', 'lala', 'haha']
list1 = List
print(List)
print(list1)
# List.sort(reverse=True)
List.clear()
print(List)
print(list1)
注意:調用clear()方法后,已經賦值給其他變量的列表也會別清空 。如List清空后,被List賦值的list1也會被清空
clear()方法相當於del list[:]
9、copy()方法
用於復制列表,返回復制后的新列表
語法:list.copy()
注意:修改List不會影響復制后的新列表,修改List中的對象,會影響復制后新列表(改列表不會互相影響,但是修改列表里面的對象會影響到對方列表里面對象)