一、什麼是Python List
Python中的List是一種可變的有序集合,可以看作是由一系列元素組成的序列,這些元素可以是不同的數據類型,如字符串、數字、布爾值等。List 中的每個元素都有一個與之對應的索引,可以通過索引來訪問 List 中的元素。List 中的元素是可變的,因此可以隨意添加、刪除或修改其中的元素。
二、Python List的基本操作
1.創建List
在Python中可以通過方括號「[]」來定義一個List對象。例如:
list1 = [1, 2, 3, 4, 5] list2 = ['a', 'b', 'c', 'd'] list3 = [1, 'a', 2, 'b']
2.訪問List中的元素
可以使用索引來訪問List中的元素,索引從0開始。例如:
list1 = [1, 2, 3, 4, 5] print(list1[0]) # 輸出 1
3.修改List中的元素
可以使用索引來修改List中的元素。例如:
list1 = [1, 2, 3, 4, 5] list1[1] = 6 print(list1) # 輸出 [1, 6, 3, 4, 5]
4.刪除List中的元素
可以使用del關鍵字來刪除List中的元素。例如:
list1 = [1, 2, 3, 4, 5] del list1[2] print(list1) # 輸出 [1, 2, 4, 5]
5.添加元素到List中
可以使用append()方法將元素添加到List中。例如:
list1 = [1, 2, 3, 4, 5] list1.append(6) print(list1) # 輸出 [1, 2, 3, 4, 5, 6]
三、Python List的常用方法
1.長度len()
用於獲取List的長度。
list1 = [1, 2, 3, 4, 5] print(len(list1)) # 輸出 5
2.添加元素append()
用於在List尾部添加一個元素。
list1 = [1, 2, 3, 4, 5] list1.append(6) print(list1) # 輸出 [1, 2, 3, 4, 5, 6]
3.插入元素insert()
用於在List指定位置插入一個元素。
list1 = [1, 2, 3, 4, 5] list1.insert(2, 6) print(list1) # 輸出 [1, 2, 6, 3, 4, 5]
4.刪除元素remove()
用於在List中刪除指定元素。
list1 = [1, 2, 3, 4, 5] list1.remove(3) print(list1) # 輸出 [1, 2, 4, 5]
5.刪除元素pop()
用於在List中刪除指定索引位置處的元素。
list1 = [1, 2, 3, 4, 5] list1.pop(2) print(list1) # 輸出 [1, 2, 4, 5]
6.查找元素index()
用於查找指定元素在List中的索引位置。
list1 = [1, 2, 3, 4, 5] print(list1.index(3)) # 輸出 2
7.計數count()
用於統計List中指定元素出現的次數。
list1 = [1, 2, 3, 4, 5, 2] print(list1.count(2)) # 輸出 2
8.排序sort()
用於對List中的元素進行排序。
list1 = [3, 2, 5, 1, 4] list1.sort() print(list1) # 輸出 [1, 2, 3, 4, 5]
9.反轉reverse()
用於將List中的元素反轉。
list1 = [1, 2, 3, 4, 5] list1.reverse() print(list1) # 輸出 [5, 4, 3, 2, 1]
10.複製copy()
用於複製一個List。
list1 = [1, 2, 3, 4, 5] list2 = list1.copy() print(list2) # 輸出 [1, 2, 3, 4, 5]
四、小結
Python List是一種常用的數據結構,可以存儲任意類型的數據,並且可以靈活地添加、刪除、修改、訪問其中的元素。通過本文大致介紹了Python List的基本操作和常用方法,希望能夠幫助讀者更好地理解和應用Python List。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/257688.html