用途:用於存一個或者多個不一樣類型的值python
定義方式:經過中括號[],存值,值之間用逗號分隔app
經常使用方法:code
l1 = [1, 2, 3, "shen"] print(l1[2]) print(l1[-1]) l1[3] = 8# >>>將l1索引3位置的值換成8
跟字符串索引切片相同,顧頭不顧尾,默認步長爲1對象
l1 = [1, 2, 3, "shen"] l1.append(100) print(l1)# >>>[1, 2, 3, 'shen', 100] l1.append("age") print(l1)# >>>[1, 2, 3, 'shen', 100, 'age'] l1.append([1,2]) print(l1)# >>>[1, 2, 3, 'shen', 100, 'age', [1, 2]]
l1 = [1, 2, 3, "shen"] l1.insert(3,"name")# 將"name"插入索引的位置 print(l1)# >>>[1, 2, 3, 'name', 'shen']
l1 = [1, 2, 3, "shen"] l1.extend([1,2,3]) print(l1) l1.extend({"name":"shen","age":18}) print(l1)
l1 = [1, 2, 3, "shen",1] l1.remove("shen") print(l1)# >>>[1, 2, 3, 1] l1.remove(1) print(l1)# >>>[2, 3, 1]
l1 = [1, 2, 3, "shen", 1] v1 = l1.pop()# 返回值是刪除的那個值 print(l1)# >>>[1,2,3,"shen"] print(v1)# >>>1 v2 = l1.pop(2)# 拿出刪除的那個值 print(l1)# >>>[1,2,"shen"] print(v2)# >>>3
l1 = [1, 2, 3, "shen", 1] # del l1# 把整個l1刪除,包括變量名 # print(l1) del l1[0]# 完全刪除索引0位置的數據 print(l1)
s1 = ['hello','world'] print("o"in s1)# >>>True
s1 = ['hello','world'] print(len(s1))
for 變量 in 可迭代對象:循環排序
.count():統計元素個數索引
l1 = [1, 2, 3, "shen", 1] print(l1.count(1))
l1 = [1, 2, 3, "shen", 1] print(l1.index(2)) print(l1.index(1,1,8))
.sort():在原列表上排序,默認從小往大排序,能夠更改倒序隊列
sorted():python的內置方法,排序後生成新的列表,原列表不變rem
l1 = [5, 2, 1, 4] # l1.sort()# 正序 l1.sort(reverse = True)# 倒序 print(l1) l2 = sorted(l1)# python的內置方法,生成新列表 print(l2) print(l1)# >>>[5,2,1,4] l2 = sorted(l1) l3 = sorted(l1,reverse=True) print(l2)# >>>[1, 2, 4, 5] print(l3)# >>>[5, 4, 2, 1] print(l1)# >>>[5, 2, 1, 4]
l1 = [5, 2, 1, 4] l1.clear() print(l1)
隊列:先進先出字符串
l1 = [] l1.append(1) print(l1) l1.append(2) print(l1) l1.append(3) print(l1) l1.pop(0) print(l1) l1.pop(0) print(l1) l1.pop(0) print(l1) # >>> [1] [1, 2] [1, 2, 3] [2, 3] [3] []
堆棧:先進後出class
l1 = [] l1.append(1) print(l1) l1.append(2) print(l1) l1.append(3) print(l1) l1.pop() print(l1) l1.pop() print(l1) l1.pop() print(l1) # >>> [1] [1, 2] [1, 2, 3] [1, 2] [1] []
列表能按索引取值,因此有序的,值變id不變,是可變類型,能夠存多個值