一、List的簡介
Python中的List是一個有序的集合,可以保存任意類型的數據,包括整數、字元串和其他對象的引用。List通過方括弧[]來表示,其中元素之間用逗號分隔。
# 創建一個包含不同數據類型的List list1 = [1, 2, "three", 4.0, ["five", 6]] # 訪問List中的元素 print(list1[0]) # 輸出 1 print(list1[2]) # 輸出 three print(list1[-1][0]) # 輸出 five
需要注意的是,List中的元素可以是任何類型的數據,甚至可以包含另一個List或其他數據類型。同時,List是一個可變的數據類型,也就是說它的值可以在程序執行過程中被修改。
二、創建List的方式
創建List的方式有兩種:通過[]創建空List,通過list()從已有的序列或其他數據類型轉換而來。
# 創建空的List list1 = [] # 或者 list1 = list() # 從已有的序列轉換而來 str1 = "Hello, world!" list2 = list(str1) print(list2) # 輸出 ['H', 'e', 'l', 'l', 'o', ',', ' ', 'w', 'o', 'r', 'l', 'd', '!'] # 從其他數據類型轉換而來 tuple1 = (1, 2, 3) list3 = list(tuple1) print(list3) # 輸出 [1, 2, 3]
三、 List的基本操作
1. 修改List
List是可變數據類型,因此可以對其進行修改。可以使用索引來直接修改List中的元素,也可以使用切片操作來替換List中的部分元素。
# 修改List中的元素 list1 = ['a', 'b', 'c', 'd'] list1[1] = 'e' print(list1) # 輸出 ['a', 'e', 'c', 'd'] # 使用切片替換List中的部分元素 list2 = ['a', 'b', 'c', 'd'] list2[1:3] = ['e', 'f'] print(list2) # 輸出 ['a', 'e', 'f', 'd']
2. 添加和刪除元素
List中提供了多種方法來添加和刪除元素。可以使用append()方法在List的末尾添加一個元素,使用insert()方法在指定位置插入一個元素,使用remove()方法刪除指定元素,使用pop()方法刪除List的指定位置的元素。
# 添加元素 list1 = ['a', 'b', 'c', 'd'] list1.append('e') print(list1) # 輸出 ['a', 'b', 'c', 'd', 'e'] # 插入元素 list2 = ['a', 'b', 'd', 'e'] list2.insert(2, 'c') print(list2) # 輸出 ['a', 'b', 'c', 'd', 'e'] # 刪除元素 list3 = ['a', 'b', 'c', 'd'] list3.remove('c') print(list3) # 輸出 ['a', 'b', 'd'] # 刪除指定位置的元素 list4 = ['a', 'b', 'c', 'd'] list4.pop(2) print(list4) # 輸出 ['a', 'b', 'd']
四、 List的高級操作
1. 列表的遍歷
List可以使用for循環進行遍歷。可以使用range()函數來生成需要遍歷的索引值,也可以直接遍歷List中的元素。
# 遍歷List中的元素 list1 = ['a', 'b', 'c'] for i in list1: print(i) # 輸出 a b c # 遍歷List中的索引值 list2 = ['a', 'b', 'c'] for i in range(len(list2)): print(i, list2[i]) # 輸出 # 0 a # 1 b # 2 c
2. 列表的排序、查詢和計數
List提供了多種方法來對其進行排序,查詢和計數。
# 按照元素首字母的ASCII碼進行排序 list1 = ['c', 'a', 'b', 'd'] list1.sort() print(list1) # 輸出 ['a', 'b', 'c', 'd'] # 反向排序 list2 = ['c', 'a', 'b', 'd'] list2.sort(reverse=True) print(list2) # 輸出 ['d', 'c', 'b', 'a'] # 查詢元素的索引值 list3 = ['a', 'b', 'c', 'c'] print(list3.index('c')) # 輸出 2 # 計算元素在List中出現的次數 list4 = ['a', 'b', 'c', 'c'] print(list4.count('c')) # 輸出 2
3. 列表的切片和連接
可以使用切片操作來獲取List中的一段元素,也可以使用+運算符來連接兩個List。
# 從List中獲取一段元素 list1 = ['a', 'b', 'c', 'd', 'e'] print(list1[1:4]) # 輸出 ['b', 'c', 'd'] # 連接兩個List list2 = ['a', 'b', 'c'] list3 = ['d', 'e', 'f'] list4 = list2 + list3 print(list4) # 輸出 ['a', 'b', 'c', 'd', 'e', 'f']
五、總結
Python中的List是一個靈活而強大的數據類型,可以用於存儲任意類型的數據,並且提供了多種基本操作和高級操作。List的靈活性和強大性使得它成為Python中不可或缺的數據類型之一。在Python編程中,掌握List的使用和操作是至關重要的。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/257929.html