列表與常用操作
列表是一個序列, 用於順序的存儲數據。列表是有序的。
列表對象操作
新建列表
方式一: 使用list函數定義空列表
In [4]: lst = list()
方式二: 使用中括號定義空列表
In [5]: lst = []
方式三: 使用中括號定義帶初始值的列表
In [6]: lst = [1, 2, 3]
方式四: 使用list函數把可迭代對象轉換爲列表
In [7]: lst = list(range(1, 10))
通常在定義列表的時候, 使用中括號, 在轉換可迭代對象爲列表時使用list函數
刪除列表對象
需要使用del方法刪除
截至2020年5月23日,本人暫時還未發現其他的方法
In [62]: lst
Out[62]: [3, 4, 5, 6, 7, 8, 9]
In [63]: del lst
In [64]: lst
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-64-b5cada25ed2a> in <module>
----> 1 lst
NameError: name 'lst' is not defined
列表元素操作(增刪查改)
訪問列表元素
- 1、通過索引訪問元素
- 2、index方法根據值返回第一個索引
- 3、count方法返回元素在列表裏的個數
index和count的時間複雜度是O(n)的, 解釋爲: 線性複雜度, 效率與數據規模線性相關
通過索引(又稱下標)訪問
- 通過下表訪問,從0開始
- 當下標超出範圍時,會拋出IndexError
- 負數索引從右邊開始, 索引從-1開始
In [13]: lst[0] # 通過下標訪問,從0開始
Out[13]: 1
In [14]: lst[10] # 當下標超出範圍時, 會拋出IndexError
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
<ipython-input-14-6ccb8eaab43e> in <module>()
----> 1 lst[10]
IndexError: list index out of range
In [15]: lst[-1] # 負數索引從右邊開始, 索引從-1開始
Out[15]: 9
In [16]: lst[-11]
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
<ipython-input-16-07dd299f10ad> in <module>()
----> 1 lst[-11]
IndexError: list index out of range
L.index通過值查找索引
- 幫助手冊:help(lst.index)
- 如存在多個值時,
index方法返回查找到的第一個索引
- L.index(value, [start, [stop]]):start參數指定從哪個索引開始查找,stop參數指定從哪個索引結束,但不包含該索引
- 當值不存在該範圍的時候, 會拋出ValueError
- 凡是stop比start小, 總是拋出ValueError
In [20]: help(lst.index)
Help on built-in function index:
index(...) method of builtins.list instance
L.index(value, [start, [stop]]) -> integer -- return first index of value.
Raises ValueError if the value is not present.
In [17]: lst.index(4) # 通過值查找索引
Out[17]: 3
In [18]: lst = [1, 2, 3, 2, 4, 3, 5]
In [19]: lst.index(2) # index方法返回查找到的第一個索引
Out[19]: 1
In [21]: lst.index(2, 2) # start參數指定從哪個索引開始查找
Out[21]: 3
In [22]: lst.index(2, 2, 3) # end參數指定到哪個索引結束, 並且不包含該索引, 當值不存在該範圍的時候, 會拋出ValueError
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-22-d805f3261138> in <module>()
----> 1 lst.index(2, 2, 3)
ValueError: 2 is not in list
In [23]: lst.index(2, 0, 3)
Out[23]: 1
In [24]: lst
Out[24]: [1, 2, 3, 2, 4, 3, 5]
In [25]: lst.index(2, -1, 0)
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-25-5c10c8921309> in <module>()
----> 1 lst.index(2, -1, 0)
ValueError: 2 is not in list
In [26]: lst.index(2, -4, -1) # start和stop可以爲負數, 但是總是從左往右查找
Out[26]: 3 # 凡是stop比start小, 總是拋出ValueError
lst.index的實現
In [27]: def index(lst, value, start = 0, stop = -1):
...: i = start
...: for x in lst[start: stop]:
...: if x == value:
...: return i
...: i += 1
...: raise ValueError()
...:
L.count(value)統計值在列表中出現的個數
如果有值則返回正常的數量,如果沒值就返回0
In [28]: help(lst.count)
Help on built-in function count:
count(...) method of builtins.list instance
L.count(value) -> integer -- return number of occurrences of value
In [29]: lst
Out[29]: [1, 2, 3, 2, 4, 3, 5]
In [30]: lst.count(2)
Out[30]: 2
In [31]: lst.count(3)
Out[31]: 2
In [32]: lst.count(5)
Out[32]: 1
In [33]: lst.count(8) # 查看不存在的值
Out[33]: 0
count方法返回值在列表裏出現的次數
count方法的實現
In [34]: def count(lst, value):
...: c = 0
...: for x in lst:
...: if x == value:
...: c += 1
...: return c
...:
修改操作
修改元素有且只有下標操作
這一種方法
下標操作修改
- 實例:lst[2] = 53
- 對超出範圍的索引會拋出IndexError
In [34]: lst
Out[34]: [1, 2, 3, 2, 4, 3, 5]
In [35]: lst[2] = 53 # 修改列表的元素直接使用下標操作取出元素並對其賦值
In [36]: lst
Out[36]: [1, 2, 53, 2, 4, 3, 5]
修改元素有且只有這一種方法
In [37]: lst[10] = 53
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
<ipython-input-37-254c500b08c1> in <module>()
----> 1 lst[10] = 53
IndexError: list assignment index out of range
對超出範圍的索引會拋出IndexError
增加操作
- L.append(object)增加
- L.insert(index, object)插入
- L.extend(iterable, /)批量添加
- list的連接操作
L.append(object)增加
原地追加、返回None
In [39]: help(lst.append)
Help on built-in function append:
append(...) method of builtins.list instance
L.append(object) -> None -- append object to end
In [40]: lst.append(9)
In [41]: lst
Out[41]: [1, 2, 53, 2, 4, 3, 5, 9]
L.insert(index, object)插入
- 原地修改list, 返回None
- insert當索引超出範圍時:
- 索引是負數, 會在第0個元素前插入
- 索引是正數, 會在最後一個元素插入
append的時間複雜度是O(1), 常數時間 效率和數據的規模無關
insert的時間複雜度是O(n), 線性時間 效率和數據規模線性相關
In [42]: help(lst.insert)
Help on built-in function insert:
insert(...) method of builtins.list instance
L.insert(index, object) -- insert object before index
In [43]: lst.insert(1, 11)
In [44]: lst
Out[44]: [1, 11, 2, 53, 2, 4, 3, 5, 9]
In [47]: lst.insert(0, 'a')
In [48]: lst
Out[48]: ['a', 1, 11, 2, 53, 2, 4, 3, 5, 9]
In [50]: lst.insert(11, 'c') # 最後一個元素插入個c
In [51]: lst
Out[51]: ['a', 3, 1, 11, 2, 53, 2, 4, 3, 5, 9, 'c']
In [52]: lst.insert(100, 'd') # 超出索引位置插入, 是插入到最後一個元素
In [53]: lst
Out[53]: ['a', 3, 1, 11, 2, 53, 2, 4, 3, 5, 9, 'c', 'd']
In [54]: lst.insert(-100, 'e')
In [55]: lst
Out[55]: ['e', 'a', 3, 1, 11, 2, 53, 2, 4, 3, 5, 9, 'c', 'd']
L.extend(iterable, /)批量添加
- 原地修改, 返回None
- 與append的區別
- append操作單個元素
- 比如插入列表,會將該列表當作一個元素插入進去,不會如extend展開
- extend操作可迭代對象
- append操作單個元素
In [56]: lst
Out[56]: ['e', 'a', 3, 1, 11, 2, 53, 2, 4, 3, 5, 9, 'c', 'd']
In [57]: lst.extend([1, 2, 3])
In [58]: lst
Out[58]: ['e', 'a', 3, 1, 11, 2, 53, 2, 4, 3, 5, 9, 'c', 'd', 1, 2, 3]
In [59]: lst.extend(range(3))
In [60]: lst
Out[60]: ['e', 'a', 3, 1, 11, 2, 53, 2, 4, 3, 5, 9, 'c', 'd', 1, 2, 3, 0, 1, 2]
append操作單個元素
extend操作可迭代對象
append操作可迭代對象時, 整個元素都append進去
In [61]: lst.append(['a', 'b', 'c'])
In [62]: lst
Out[62]: ['e', 3, 0, 1, 2, ['a', 'b', 'c']]
list的連接操作
不修改list本身, 返回一個新list, 這叫list的連接操作
In [69]: lst = list(range(5))
In [70]: lst + ['a', 'b', 'c'] # 不修改list本身, 返回一個新list, 這叫list的連接操作
Out[70]: [0, 1, 2, 3, 4, 'a', 'b', 'c']
In [71]: lst # 並不修改list本身, 會生成一塊新的內存
Out[71]: [0, 1, 2, 3, 4]
刪除操作
- L.remove(value)根據值刪除
- L.pop([index])根據索引刪除並返回刪除的數據
- L.clear()刪除所有元素
- del方法根據索引刪除
L.remove(value)根據值刪除
- 原地修改, 返回None
- 當有多個值時從左至右刪除第一個
- 當值不存在的時候, 會拋出ValueError
In [72]: help(lst.remove)
Help on built-in function remove:
remove(...) method of builtins.list instance
L.remove(value) -> None -- remove first occurrence of value.
Raises ValueError if the value is not present.
In [73]: lst = [1, 2, 3, 2, 4, 3, 5, 3, 4]
In [74]: lst
Out[74]: [1, 2, 3, 2, 4, 3, 5, 3, 4]
In [75]: lst.remove(1) # 原地修改, 返回None, 根據值刪除元素
In [76]: lst
Out[76]: [2, 3, 2, 4, 3, 5, 3, 4]
In [77]: lst.remove(2) # 從左至右刪除第一個
In [78]: lst
Out[78]: [3, 2, 4, 3, 5, 3, 4]
In [79]: lst.remove(10) # 當值不存在的時候, 會拋出ValueError
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-79-0db5c9e7363a> in <module>()
----> 1 lst.remove(10)
ValueError: list.remove(x): x not in list
L.pop([index])根據索引刪除並返回刪除的數據
- lst.pop():返回並刪除最後一個元素
- lst.pop(1):返回並刪除索引所在位置的元素
- 當索引不存在時, 拋出IndexError
- pop和remove的區別是pop根據索引刪除元素, 並且會返回刪除的元素
In [81]: help(lst.pop)
Help on built-in function pop:
pop(...) method of builtins.list instance
L.pop([index]) -> item -- remove and return item at index (default last).
Raises IndexError if list is empty or index is out of range.
In [80]: lst.pop() # 返回並刪除最後一個元素
Out[80]: 4
In [82]: lst
Out[82]: [3, 2, 4, 3, 5, 3]
In [83]: lst.pop(1) # 返回並刪除索引所在位置的元素
Out[83]: 2
In [84]: lst
Out[84]: [3, 4, 3, 5, 3]
In [85]: lst.pop(100) # 當索引不存在時, 拋出IndexError
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
<ipython-input-85-795b88347eea> in <module>()
----> 1 lst.pop(100)
IndexError: pop index out of range
pop不傳遞index參數, 時間複雜度是O(1)
pop傳遞index參數, 時間複雜度是O(n)
pop和remove的區別是pop根據索引刪除元素, 並且會返回刪除的元素
remove根據值刪除元素, 返回None
L.clear()刪除所有元素
In [86]: lst.clear() # 刪除所有元素
In [87]: lst
Out[87]: []
del方法刪除
- del方法是根據索引刪除元素的
- 刪除單個元素:del lst[0]
- 刪除連續的多個元素:del lst[0:3]
In [57]: lst
Out[57]: ['1', 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
In [58]: del lst[0]
In [59]: lst
Out[59]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
In [60]: del lst[0:3]
In [61]: lst
Out[61]: [3, 4, 5, 6, 7, 8, 9]
其他操作
- 求list長度: len
- 反轉列表reverse()方法
- 排序sort方法
- 淺copy與深copy
求list長度: len
In [88]: lst = list(range(4))
In [89]: lst
Out[89]: [0, 1, 2, 3]
In [90]: len(lst)
Out[90]: 4
反轉列表reverse()方法
In [92]: lst.reverse() # 原地修改, 返回None, 反轉列表
In [94]: lst
Out[94]: [3, 2, 1, 0]
排序sort方法
In [96]: help(lst.sort)
Help on built-in function sort:
sort(...) method of builtins.list instance
L.sort(key=None, reverse=False) -> None -- stable sort *IN PLACE*
In [95]: lst = [3, 1, 2, 4, 5, 7, 3, 2]
In [97]: lst.sort() # 原地修改, 返回None
In [98]: lst
Out[98]: [1, 2, 2, 3, 3, 4, 5, 7]
In [99]: lst.sort(reverse=True) # 逆序排列
In [100]: lst
Out[100]: [7, 5, 4, 3, 3, 2, 2, 1]
淺copy與影子拷貝以及深copy
In [101]: lst = list(range(3))
In [102]: lst
Out[102]: [0, 1, 2]
In [103]: lst2 = lst
In [104]: lst2[1] = 5 # lst2值修改了
In [105]: lst2
Out[105]: [0, 5, 2]
In [106]: lst # lst值改變了
Out[106]: [0, 5, 2]
複製操作是傳遞是引用, 也叫淺拷貝
copy方法
In [107]: help(lst.copy)
Help on built-in function copy:
copy(...) method of builtins.list instance
L.copy() -> list -- a shallow copy of L
In [108]: lst
Out[108]: [0, 5, 2]
In [109]: lst2 = lst.copy() # 影子拷貝
In [110]: lst2[1] = 2
In [111]: lst2
Out[111]: [0, 2, 2]
In [113]: lst
Out[113]: [0, 5, 2]
In [114]: lst = [1, [1, 2, 3], 2]
In [115]: lst2 = lst.copy()
In [116]: lst2[1][1] = 5
In [117]: lst2
Out[117]: [1, [1, 5, 3], 2]
In [118]: lst # lst依然改變了
Out[118]: [1, [1, 5, 3], 2]
賦值操作, 對可變對象是引用傳遞, 對不可變對象是值傳遞
深複製方法:
In [119]: import copy
In [120]: lst2 = copy.deepcopy(lst)
In [121]: lst2
Out[121]: [1, [1, 5, 3], 2]
In [122]: lst2[1][1] = 7
In [123]: lst2
Out[123]: [1, [1, 7, 3], 2]
In [124]: lst
Out[124]: [1, [1, 5, 3], 2]