列表簡介
列表(list) 是Python基本數據類型之一,是一種可變序列、可以存儲各種數據類型的集合,用 [] 表示一個列表的開始和結束,元素之間使用 , 分隔,列表中的每個元素都有對應下標,下標從0開始。
列表基本操作
列表 支持對集合中元素進行增加、查找、刪除、排序、合併等操作,常用方法下表所示:
方法 | 功能 |
---|---|
append | 在列表尾部增加元素 |
insert | 在列表指定位置插入元素 |
index | 返回指定元素的下標 |
remove | 從左到右遍歷列表,刪除第1個匹配的元素 |
clear | 清空列表 |
sort | 對列表中元素進行排序(列表中的元素需要相同類型) |
count | 統計元素在當前列表中的個數 |
extend | 合併兩個列表 |
reverse | 永久反轉列表 |
copy | 淺拷貝列表 |
pop | 刪除並返回指定下標對應的元素 |
在Python IDLE中可以通過help函數查看對應說明。
增加&插入
>>> test_list = [] #聲明空列表
>>> test_list.append(1) #調用append方法追加元素1
>>> test_list
[1]
>>> test_list.insert(0, 2) #調用insert方法在0下標位置插入元素2
>>> test_list
[2, 1]
刪除&清空
>>> test_list = [2, 1]
>>> test_list.pop(0) #刪除0位置元素
2
>>> test_list
[1]
>>> test_list = [1, 2, 3]
>>> test_list.remove(3) #刪除列表中元素3
>>> test_list
[1, 2]
>>> test_list = [3, 1, 2, 3]
>>> test_list.remove(3) #可以看出刪除的是左邊第1個3元素
>>> test_list
[1, 2, 3]
>>> test_list.remove(5) #刪除一個不存在的元素時,拋出ValueError
Traceback (most recent call last):
File "<pyshell#18>", line 1, in <module>
test_list.remove(5)
ValueError: list.remove(x): x not in list
>>> test_list = [1, 2, 3]
>>> test_list.clear() #清空列表
>>> test_list
[]
複製
>>> test_list = [1, 2, 3] #聲明test_list列表爲[1,2,3]
>>> test_list2 = test_list.copy() #copy
>>> test_list2
[1, 2, 3]
>>> id(test_list)
45812360
>>> id(test_list2)
46149960
統計指定元素個數
>>> test_list = [1, 2, 3, 1]
>>> test_list.count(1) #統計test_list列表中元素爲1的個數
2
>>> test_list.count(4)
0
查找
>>> test_list = [1, 2, 3, 4]
>>> test_list.index(1) #在test_list查找元素1的下標
0
>>> test_list.index(5) #如果列表中並沒有這個元素,拋出ValueError
Traceback (most recent call last):
File "<pyshell#19>", line 1, in <module>
test_list.index(5)
ValueError: 5 is not in list
排序&反轉
>>> test_list = [1, 3, 2, 4]
>>> test_list.sort() #排序,默認正序
>>> test_list
[1, 2, 3, 4]
>>> test_list.sort(reverse=True) #倒序
>>> test_list
[4, 3, 2, 1]
>>> test_list = [1, 3, 2, 'Python']
>>> test_list.sort() #列表中元素不同類型會拋出TypeError
Traceback (most recent call last):
File "<pyshell#8>", line 1, in <module>
test_list.sort()
TypeError: '<' not supported between instances of 'str' and 'int'
>>> test_list = ['Python', 'Java', 'Android', 'iOS']
>>> test_list.reverse() #列表反轉
>>> test_list
['iOS', 'Android', 'Java', 'Python']
合併兩個列表
>>> test_list1 = [1, 2, 3]
>>> test_list2 = [4, 5, 6]
>>> test_list1.extend(test_list2) #將test_list2的元素合併到test_list1中
>>> test_list1
[1, 2, 3, 4, 5, 6]
>>> test_list2
[4, 5, 6]
查看指定下標元素&遍歷
>>> test_list = ['Python', 'Java', 'Android', 'iOS']
>>> test_list[0] #查看下標爲0的元素
'Python'
>>> test_list[1] #查看下標爲1的元素
'Java'
>>> test_list[2] #查看下標爲2的元素
'Android'
>>> test_list[3] #查看下標爲3的元素
'iOS'
>>> test_list[4] #查看下標爲4的元素,這裏沒有下標爲4,拋出IndexError
Traceback (most recent call last):
File "<pyshell#14>", line 1, in <module>
test_list[4]
IndexError: list index out of range
------------------------------------------------------------
>>> test_list = ['Python', 'Java', 'Android', 'iOS']
>>> test_list[:] #切片
['Python', 'Java', 'Android', 'iOS']
>>> for item in test_list: #for循環
print(item)
Python
Java
Android
iOS