一、列表的創建
列表在Python中非常常見,可以通過多種方式進行創建。
1.1 使用方括號[]創建:
list1 = [1, 2, 3]
print(list1) #[1, 2, 3]
1.2 使用list()函數創建:
list2 = list("hello")
print(list2) #['h', 'e', 'l', 'l', 'o']
二、列表的索引和切片
2.1 列表索引:
列表可以使用下標進行索引,其中第一個元素的下標為0,以此類推。
list1 = [1, 2, 3]
print(list1[0]) #1
print(list1[2]) #3
2.2 列表切片:
除了索引單個元素外,還可以使用冒號分隔的下標進行切片,返回一個新的列表。
list1 = [1, 2, 3, 4, 5]
print(list1[1:3]) #[2, 3]
三、列表的遍歷
3.1 for循環遍歷:
通過for循環遍歷列表中的元素,可以使用in關鍵字。
list1 = [1, 2, 3, 4, 5]
for x in list1:
print(x)
3.2 while循環遍歷:
通過while循環和len()函數可以進行列表的遍歷。
list1 = [1, 2, 3, 4, 5]
i = 0
while i < len(list1):
print(list1[i])
i += 1
四、列表的操作
4.1 添加元素:
通過append()方法可以往列表中添加新的元素。
list1 = [1, 2, 3]
list1.append(4)
print(list1) #[1, 2, 3, 4]
4.2 刪除元素:
通過remove()方法可以刪除列表中的特定元素。
list1 = [1, 2, 3, 4, 5]
list1.remove(3)
print(list1) #[1, 2, 4, 5]
4.3 修改元素:
通過下標可以修改列表中的元素。
list1 = [1, 2, 3, 4, 5]
list1[3] = 99
print(list1) #[1, 2, 3, 99, 5]
五、列表的統計方法
5.1 統計列表長度:
使用len()方法可以獲取列表中元素的數量。
list1 = [1, 2, 3, 4, 5]
print(len(list1)) #5
5.2 統計元素出現次數:
使用count()方法可以統計列表中特定元素的出現次數。
list1 = [1, 2, 3, 4, 5, 2, 3]
print(list1.count(2)) #2
以上就是對Python List實用技巧的總結,包括列表的創建、索引和切片、遍歷、操作以及統計方法等內容。在實際編程中,掌握列表的使用技巧對於提升編碼效率是非常有幫助的。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/159330.html