本篇講列表的操作與維護
直接代碼演示吧
1.講字符串轉換為列表
1 #列表的維護 2 #將字符串轉換為列表 3 print(list("hello"))
輸出結果
['h', 'e', 'l', 'l', 'o']
2.修改元素
1 #修改元素 2 x = [1,2,3,4,5]; 3 x[1]=0 4 print(x)
輸出結果
[1, 0, 3, 4, 5]
3.增加元素
#增加元素 append() names = ["a","b","c","d"] #append()僅支持添加一個元素 names.append("e") #extend()增加一個列表 names.extend(["e","f"]) #insert()根據索引添加元素 names.insert(1,"t") print(names)
輸出結果
['a', 't', 'b', 'c', 'd', 'e', 'e', 'f']
4.刪除
1 #刪除remove()刪除指定值的元素 2 x = [1,2,3,4,5] 3 x.remove(2) 4 print("--------刪除2----------") 5 print(x) 6 names=["Alice","Linda","Bob"] 7 names.remove("Bob") 8 print("--------刪除BOb----------") 9 print(names) 10 11 #del 根據索引刪除元素 12 numbers = [6,7,8,9,10,11] 13 del numbers[1] 14 print("--------刪除索引1----------") 15 print(numbers) 16 17 # pop()根據索引刪除元素 18 numbers1 = [6,7,8,9,10,11] 19 numbers1.pop(1) 20 print("--------刪除索引1----------") 21 print(numbers1) 22 numbers1.pop() 23 print("--------刪除最后一個元素----") 24 print(numbers1)
輸出結果
--------刪除2---------- [1, 3, 4, 5] --------刪除BOb---------- ['Alice', 'Linda'] --------刪除索引1---------- [6, 8, 9, 10, 11] --------刪除索引1---------- [6, 8, 9, 10, 11] --------刪除最后一個元素---- [6, 8, 9, 10]
5.分片賦值
1 #分片賦值 2 str1 = ["a","b","c"] 3 # 替換索引>=2 4 str1[2:] = list("de") 5 print("替換索引>=2結果 :",str1) 6 #刪除索引2 7 str1[2:2] = "f" 8 print("刪除索引2結果 :",str1) 9 #賦值且替換索引2-3 10 str1[2:4] = ["g","h","i"] 11 print("賦值且替換索引2-3結果 :",str1) 12 #刪除元素 13 str1[:] = [] 14 print("刪除所有結果 :",str1)
輸出結果
替換索引>=2結果 : ['a', 'b', 'd', 'e'] 刪除索引2結果 : ['a', 'b', 'f', 'd', 'e'] 賦值且替換索引2-3結果 : ['a', 'b', 'g', 'h', 'i', 'e'] 刪除所有結果 : []
6.搜索元素
1 #搜索元素 2 names1=["Alice","Linda","Bob"] 3 if "Alice" in names1: 4 print(True) 5 else: 6 print(False)
輸出結果
True
7.搜索元素索引值
1 #index()元素索引值 2 str1 = ["a","b","c"] 3 print(str1.index("a"))
輸出結果
0
8.統計元素出現次數
1 #count()統計某元素出現次數 2 number1 = [1,2,1,3,4] 3 print(number1.count(1))
輸出結果
2
9.反向存放
1 #reverse將列表中的元素反向存放,返回值為null 2 number1 = [1,2,1,3,4] 3 number1.reverse(); 4 print(number1)
輸出結果
[4, 3, 1, 2, 1]
10.排序
1 #sort()方法:對元素進行排序,返回值為null 2 number1 = [1,2,1,3,4] 3 number1.sort() 4 print(number1) 5 #sorted()返回值為排序后的數組 6 number2 = [1,2,1,3,4] 7 y=sorted(number2); 8 print(y) 9 print(number2)
輸出結果
[1, 1, 2, 3, 4] [1, 1, 2, 3, 4] [1, 2, 1, 3, 4]