Python學習之路-list的常用方法
阿新 • • 發佈:2018-02-21
mov color copy dex span pen int 切片 python學習
增
- append()
- insert(index,obj) #可以向指定位置添加
1 __author__ = "KuanKuan" 2 list = [] 3 list.append("JankinYu") 4 list.insert(0,"kali") 5 print(list)
#輸出結果
#[‘kali‘, ‘JankinYu‘]
刪
- pop()#可以刪除指定位置如果不給參數默認刪除最後一個
- remove()#可以刪除指定的一個值
- del
-
list1 = ["JankinYu","kuankuan","梳子","卡農"]
print(list1)
list1.remove(
#[‘JankinYu‘, ‘kuankuan‘, ‘梳子‘, ‘卡農‘]
#[‘JankinYu‘, ‘kuankuan‘, ‘卡農‘] #[‘JankinYu‘, ‘kuankuan‘] #[‘JankinYu‘]
改
- list[index]=value
-
list3 = [‘1‘,‘2‘,‘3‘,‘4‘,‘5‘,‘6‘,‘7‘,‘8‘,‘9‘] list3[8] = 666 print(list3) #輸出結果 #[‘1‘, ‘2‘, ‘3‘, ‘4‘, ‘5‘, ‘6‘, ‘7‘, ‘8‘, 666]
查
- index()#查找值的下標
- 切片list[start:end:step]
list3 = [‘1‘,‘2‘,‘3‘,‘4‘,‘5‘,‘6‘,‘7‘,‘8‘,‘9‘] print(list3[0:9:2]) print("取list3裏下標0-4的值:",list3[0:5]) print(list3) #輸出結果 #[‘1‘, ‘3‘, ‘5‘, ‘7‘, ‘9‘] #取list3裏下標0-4的值: [‘1‘, ‘2‘, ‘3‘, ‘4‘, ‘5‘] #8
拷貝
-
- 別名綁定:list1=list2
- 淺拷貝4種方式
- names1 = names.copy() # 淺copy 相當於copy.copy()
- names2 = copy.copy(names)
- names3 = names[:]
- names4 = list(names)
深拷貝:list2=copy.deepcopy(list1)
1 __author__ = "KuanKuan" 2 import copy 3 list_name=[1,2,3,4,5] 4 name=list_name.copy() 5 print(name) 6 name1=copy.copy(list_name) 7 print(name1) 8 name2=list_name[:] 9 print(name2) 10 name3=list(list_name) 11 print(list_name) 12 b=copy.deepcopy(list_name) 13 print(b)
其他
-
- 計數:count()
- 反轉:reverse()
- 排序:sort() # 按照ascii碼表的排序規則
- 擴展:extend()
- 遍歷:for…in…
- 清空:clear()
Python學習之路-list的常用方法