1、數據結構與獲取幫助信息
python
一、數據結構算法
經過某種方式(例如對元素進行編號)組織在一塊兒的數據元素的集合,這些數據元素能夠是數字或者字符,甚至能夠是其它的數據結構。bash
python的最基本數據結構是序列數據結構
序列中的每一個元素被分配一個序號(即元素的位置),也稱爲索引:索引從0開始編號app
二、python中如何獲取命令幫助
ssh
獲取對象支持使用的屬性和方法:dir(),ide
某方法的具體使用幫助:help()函數
獲取可調用對象的文檔字串:print(obj.__doc__)ui
In [15]: dir(list) Out[15]: ['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort'] In [17]: help(list) Help on list object: class list(object) | list() -> new empty list | list(iterable) -> new list initialized from iterable's items | | Methods defined here: | | __add__(self, value, /) | Return self+value. | | __contains__(self, key, /) | Return key in self. | | __delitem__(self, key, /) | Delete self[key]. | | __eq__(self, value, /) | Return self==value. | | __ge__(self, value, /) | Return self>=value. In [20]: print(list.__doc__) list() -> new empty list list(iterable) -> new list initialized from iterable's items In [21]: list.__doc__ Out[21]: "list() -> new empty list\nlist(iterable) -> new list initialized from iterable's items"
2、列表
spa
一、列表
列表:是一個任意類型的對象的位置相關的有序集合。
列表是一個序列,用於順序的存儲數據
列表的定義和初始化:
In [5]: lst1 = list() # 使用工廠函數list() In [6]: lst2 = [] # 使用[] In [7]: type(lst1) Out[7]: list In [8]: type(lst2) Out[8]: list In [9]: lst1 = list(range(10)) # 將一個可迭代對象轉化爲列表 In [10]: lst1 Out[10]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
一般在定義列表的時候使用中括號,在轉化可迭代對象爲列表時用list()
3、列表相關的操做
對列表通常有增、刪、改、查的相關操做
一、查
1)經過索引(下標)訪問列表的元素
返回該索引對應的元素
索引從左邊開始,從0開始,不能超出範圍,不然拋出IndexError
負數索引從右邊開始,從-1開始
In [25]: lst1 Out[25]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] In [26]: lst1[0] Out[26]: 0 In [27]: lst1[10] --------------------------------------------------------------------------- IndexError Traceback (most recent call last) <ipython-input-27-255d55760a91> in <module>() ----> 1 lst1[10] IndexError: list index out of range In [28]: lst1[-1] Out[28]: 9 In [29]: lst1[-3] Out[29]: 7 In [30]: lst1[-3]
2)list.index()
返回查找到該元素的第一個索引
若是該元素不存在,則拋出ValueError
start參數指定從哪一個索引開始查找;stop參數指定從哪一個索引結束,而且不包含該索引
start和stop能夠爲負數,可是老是從左往右查找
In [51]: help(lst2.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 [47]: lst2=[1, 3, 5, 2, 3, 5] In [48]: lst2.index(3) Out[48]: 1 In [49]: lst2.index(2) Out[49]: 3 In [52]: lst2.index(8) --------------------------------------------------------------------------- ValueError Traceback (most recent call last) <ipython-input-52-857c8a1f260a> in <module>() ----> 1 lst2.index(8) ValueError: 8 is not in list In [56]: lst2.index(3, 3) Out[56]: 4 In [57]: lst2.index(3, 3, 4) --------------------------------------------------------------------------- ValueError Traceback (most recent call last) <ipython-input-57-dd5e9d56cf7c> in <module>() ----> 1 lst2.index(3, 3, 4) ValueError: 3 is not in list In [59]: lst2.index(3, 3, 5) Out[59]: 4 In [60]: lst2.index(3, 4, 5) Out[60]: 4 In [70]: lst2.index(3, -1, -6,) # start 大於 stop 是一個空列表 --------------------------------------------------------------------------- ValueError Traceback (most recent call last) <ipython-input-70-b3ae59853639> in <module>() ----> 1 lst2.index(3, -1, -6,) ValueError: 3 is not in list In [71]: lst2.index(3, -6, -1,) Out[71]: 1 In [74]: lst2.index(3, -6, 9,) In [98]: lst2.index(3, 1, 1) --------------------------------------------------------------------------- ValueError Traceback (most recent call last) <ipython-input-98-a95f8fe9908b> in <module>() ----> 1 lst2.index(3, 1, 1) ValueError: 3 is not in list In [99]: lst2.index(3, 1, 2) Out[99]: 1
list.index()函數的實現原型:
def index(lst, value, start = 0, stop = -1): i = start for x in lst[start: end] if x == value: return i i += 1 rais ValueError()
3)list.count()
返回該值在列表中出現的次數
In [89]: lst2 Out[89]: [1, 3, 5, 2, 3, 5] In [90]: lst2.count(1) Out[90]: 1 In [91]: lst2.count(5) Out[91]: 2 In [92]: lst2.count(8) Out[92]: 0
原型:
def count(lst, value): c = 0 for x in lst: if x == value: c += 1 return c
小結:
index()和count()的時間複雜度是O(n),也稱線性複雜度;效率與數據規模線性相關
二、改
對列表中元素的修改
修改列的元素直接使用索引取出元素並對其賦值;有且只有這一種方法能對list的單個元素作修改
In [7]: lst1 = [1, 3, 5, 2, 3, 4, 5, 6] In [8]: lst1[2] Out[8]: 5 In [9]: lst1[2] = 55 In [10]: lst1 Out[10]: [1, 3, 55, 2, 3, 4, 5, 6] In [12]: lst1[15] = 15 --------------------------------------------------------------------------- IndexError Traceback (most recent call last) <ipython-input-12-4bd87b980f30> in <module>() ----> 1 lst1[15] = 15 IndexError: list assignment index out of range
三、增
顯然不能經過索引來增長元素
1)list.append()
原地修改list,在最後增長一個元素;返回結果是None
In [13]: lst1 Out[13]: [1, 3, 55, 2, 3, 4, 5, 6] In [14]: lst1.append(9) In [15]: lst1 Out[15]: [1, 3, 55, 2, 3, 4, 5, 6, 9] In [16]: lst2 = ["a", "b"] In [17]: lst1.append(lst2) In [18]: lst1 Out[18]: [1, 3, 55, 2, 3, 4, 5, 6, 9, ['a', 'b']]
2)list.insert()
在給定索引前插入一個元素;返回None
當給定的索引超過左邊範圍時,會在第0個元素前插入;超過右邊的範圍時,會在最後一個元素後插入
In [24]: lst1 Out[24]: [1, 3, 55, 2, 3, 4, 5, 6, 9, ['a', 'b'], 'xj'] In [25]: lst1.insert("x") --------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-25-8414f7ee6bf3> in <module>() ----> 1 lst1.insert("x") TypeError: insert() takes exactly 2 arguments (1 given) In [26]: lst1.insert(0, "x") In [27]: lst1 Out[27]: ['x', 1, 3, 55, 2, 3, 4, 5, 6, 9, ['a', 'b'], 'xj'] In [28]: lst1.insert(20, "j") In [29]: lst1 Out[29]: ['x', 1, 3, 55, 2, 3, 4, 5, 6, 9, ['a', 'b'], 'xj', 'j']
3)list.extend()
接受一個可迭代對象,將其擴展到列表後面;返回None
In [39]: lst1 = [1, 2, 3] In [40]: lst2 = ["a", "b", "c"] In [41]: lst1.extend(lst2) In [42]: lst1 Out[42]: [1, 2, 3, 'a', 'b', 'c'] In [43]: lst1.extend("xxj") In [44]: lst1 Out[44]: [1, 2, 3, 'a', 'b', 'c', 'x', 'x', 'j']
4)+
不修改list自己,返回一個新的list,是list的鏈接操做
In [46]: lst1 Out[46]: [1, 2, 3, 'a', 'b', 'c', 'x', 'x', 'j'] In [47]: lst2 Out[47]: ['a', 'b', 'c'] In [48]: lst1 + lst2 Out[48]: [1, 2, 3, 'a', 'b', 'c', 'x', 'x', 'j', 'a', 'b', 'c'] In [49]: lst1 + ["A", "B"] Out[49]: [1, 2, 3, 'a', 'b', 'c', 'x', 'x', 'j', 'A', 'B']
小結:
append的時間複雜度是o(1),也被稱爲常數時間,效率和數據的規模無關
insert的時間複雜度是o(n),線性時間,效率和數據規模線性相關
append()操做單個元素至list尾部
extend()操做可迭代對象至list尾部
時間複雜度:是一種定性的描述一個算法的效率
四、刪
1)list.remove()
刪除給定值,原地修改,返回None
從左往右,刪除第一個
In [60]: lst1 Out[60]: [1, 2, 3, 'a', 'b', 'c', 'x', 'x', 'j', 'a', 'b', 'c'] In [61]: lst1.remove("a") In [62]: lst1 Out[62]: [1, 2, 3, 'b', 'c', 'x', 'x', 'j', 'a', 'b', 'c'] In [63]: lst1.remove(5) --------------------------------------------------------------------------- ValueError Traceback (most recent call last) <ipython-input-63-129875e67ef4> in <module>() ----> 1 lst1.remove(5) ValueError: list.remove(x): x not in list
2)list.pop()
刪除給定索引對應的元素;不給定索引則刪除最後一個索引所對應的元素
原地修改,返回該元素;
In [67]: lst1 Out[67]: [1, 2, 3, 'b', 'c', 'x', 'x', 'j', 'a', 'b', 'c'] In [68]: lst1.pop() Out[68]: 'c' In [69]: lst1 Out[69]: [1, 2, 3, 'b', 'c', 'x', 'x', 'j', 'a', 'b'] In [70]: lst1.pop(2) Out[70]: 3 In [72]: lst1.pop(15) --------------------------------------------------------------------------- IndexError Traceback (most recent call last) <ipython-input-72-02c3871eac43> in <module>() ----> 1 lst1.pop(15) IndexError: pop index out of range
小結:
pop()不傳遞Index參數時,時間複雜度O(1)
pop()傳遞index參數時,時間複雜度O(n)
pop()根據索引刪除元素,返回刪除的元素
remove根據值刪除元素,返回None
3)list.clear()
刪除list的全部元素
In [73]: lst1 Out[73]: [1, 2, 'b', 'c', 'x', 'x', 'a', 'b'] In [74]: lst1.clear() In [75]: lst1 Out[75]: []
4)del()
del()是python內置函數,刪除一個對象
In [167]: lst1 Out[167]: [1, ['a', 'b'], 2] In [168]: del(lst1[1]) In [169]: lst1 Out[169]: [1, 2] In [170]: del(lst1) In [171]: lst1 --------------------------------------------------------------------------- NameError Traceback (most recent call last) <ipython-input-171-f3e10dd48749> in <module>() ----> 1 lst1 NameError: name 'lst1' is not defined
五、list的其它操做
1)求list的長度
len()是Python內置的函數
In [76]: lst1 Out[76]: [] In [77]: len(lst1) Out[77]: 0 In [78]: lst1 =list(range(5)) In [79]: lst1 Out[79]: [0, 1, 2, 3, 4] In [80]: len(lst1) Out[80]: 5
2)反轉list的元素順序
In [81]: lst1.reverse() In [82]: lst1 Out[82]: [4, 3, 2, 1, 0]
3)排序
In [86]: print(lst1.sort.__doc__) L.sort(key=None, reverse=False) -> None -- stable sort *IN PLACE* In [87]: lst1 Out[87]: [4, 3, 2, 1, 0] In [88]: lst1.sort() In [89]: lst1 Out[89]: [0, 1, 2, 3, 4] In [90]: lst1.append("a") In [91]: lst1 Out[91]: [0, 1, 2, 3, 4, 'a'] In [92]: lst1.sort() --------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-92-0b68de07ed2f> in <module>() ----> 1 lst1.sort() TypeError: '<' not supported between instances of 'str' and 'int'
4)複製
In [105]: lst1 Out[105]: [0, 1, 2, 3, 4] In [106]: lst2 = lst1 # 賦值操做是引用傳遞 In [107]: lst2 Out[107]: [0, 1, 2, 3, 4] In [108]: lst2[1] Out[108]: 1 In [109]: lst2[1] = 11 In [110]: lst2[1] Out[110]: 11 In [111]: lst2 Out[111]: [0, 11, 2, 3, 4] In [112]: lst1 Out[112]: [0, 11, 2, 3, 4]
賦值操做是引用傳遞,也被稱爲淺複製,淺拷貝;建立一個新的變量名,指向同一個內存對象
list.copy()
影子拷貝,並非深拷貝
In [113]: lst1 Out[113]: [0, 11, 2, 3, 4] In [114]: lst2 = lst1.copy() In [115]: lst2 Out[115]: [0, 11, 2, 3, 4] In [116]: lst2[1] = "a" In [117]: lst2 Out[117]: [0, 'a', 2, 3, 4] In [118]: lst1 Out[118]: [0, 11, 2, 3, 4]
深拷貝:
複製操做,對可變對象是引用傳遞,對不可變對象是值傳遞
In [123]: lst1 = [1, ["a", "b"], 2] In [124]: lst1[1] Out[124]: ['a', 'b'] In [125]: lst2 = lst1 # 淺複製,引用傳遞 In [126]: lst2 Out[126]: [1, ['a', 'b'], 2] In [127]: lst2[1] = 0 In [128]: lst2 Out[128]: [1, 0, 2] In [129]: lst1 Out[129]: [1, 0, 2] In [130]: lst1 = [1, ["a", "b"], 2] In [131]: lst2 = lst1.copy() # 影子複製,原樣複製一份原內存對象,只對第一層 In [132]: lst2 Out[132]: [1, ['a', 'b'], 2] In [133]: lst2[1] = 0 In [134]: In [134]: lst2 Out[134]: [1, 0, 2] In [135]: lst1 Out[135]: [1, ['a', 'b'], 2] In [136]: lst2 = lst1.copy() In [137]: lst2 Out[137]: [1, ['a', 'b'], 2] In [138]: lst2[1][1] = 9 In [139]: lst2 Out[139]: [1, ['a', 9], 2] In [140]: lst1 Out[140]: [1, ['a', 9], 2] ## copy.deepcopy() In [149]: import copy In [150]: lst1 = [1, ["a", "b"], 2] In [151]: lst2 = copy.deepcopy(lst1) # 針對多層 In [152]: lst2 Out[152]: [1, ['a', 'b'], 2] In [153]: lst2[1][1] = 9 In [154]: lst2 Out[154]: [1, ['a', 9], 2] In [155]: lst1 Out[155]: [1, ['a', 'b'], 2]
4、元祖
一、元祖的定義和初始化
In [197]: t Out[197]: () In [198]: t = () In [199]: t Out[199]: () In [200]: t = (1, 2) In [201]: t Out[201]: (1, 2) In [202]: t = 1, 2 # ()可省略 In [203]: t Out[203]: (1, 2) In [55]: s = 1 In [56]: type(s) Out[56]: int In [57]: s = 1, In [58]: type(s) Out[58]: tuple In [59]: s Out[59]: (1,) In [204]: print(tuple.__doc__) tuple() -> empty tuple tuple(iterable) -> tuple initialized from iterable's items If the argument is a tuple, the return value is the same object. In [205]: t = tuple() # 工廠函數tuple() In [206]: t Out[206]: () In [207]: t= tuple([1, 2, 3]) In [208]: t Out[208]: (1, 2, 3) In [209]: t= tuple((1, 2)) In [210]: t Out[210]: (1, 2)
二、元祖的操做
1)索引操做
In [211]: t Out[211]: (1, 2) In [212]: t[1] Out[212]: 2 In [213]: t[1] = 2 # 元祖是不可變的,不能原地修改 --------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-213-9d97237db197> in <module>() ----> 1 t[1] = 2 TypeError: 'tuple' object does not support item assignment In [214]: t Out[214]: (1, 2) In [218]: t = (1, ["a", "b"]) In [219]: t Out[219]: (1, ['a', 'b']) In [220]: t[1] Out[220]: ['a', 'b'] In [221]: t[1] = 3 --------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-221-636819fa7dc7> in <module>() ----> 1 t[1] = 3 TypeError: 'tuple' object does not support item assignment In [222]: t[1][1] = 3 In [223]: t Out[223]: (1, ['a', 3])
2)count,index()
tuple的方法只有tuple.count()和tuple.index(),表如今list中是徹底同樣的:
In [225]: t Out[225]: (1, ['a', 'b']) In [226]: t.count(1) Out[226]: 1 In [227]: t.index(1) Out[227]: 0 In [228]: t.index(a) --------------------------------------------------------------------------- NameError Traceback (most recent call last) <ipython-input-228-7a95a64370b2> in <module>() ----> 1 t.index(a) NameError: name 'a' is not defined In [229]: t.index("a") --------------------------------------------------------------------------- ValueError Traceback (most recent call last) <ipython-input-229-71f0f19bbabb> in <module>() ----> 1 t.index("a") ValueError: tuple.index(x): x not in tuple In [230]: t.index(["a", "b"]) Out[230]: 1
三、命名元祖
能夠經過名字替代索引來訪問元素,其它方面的屬性和元祖同樣
In [231]: t = ("xxj", 18) In [232]: t Out[232]: ('xxj', 18) In [233]: t[0] Out[233]: 'xxj' In [234]: t[1] Out[234]: 18 In [235]: from collections import namedtuple # 導入collectons模塊的namedtuple類 In [236]: User = namedtuple('_Yonghu', ["name", "age"]) # 類初始化 In [237]: User Out[237]: __main__._Yonghu In [240]: me = User("xxj", 18) In [241]: me Out[241]: _Yonghu(name='xxj', age=18) In [242]: me.name Out[242]: 'xxj' In [243]: me.name() --------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-243-658c183ca1b1> in <module>() ----> 1 me.name() TypeError: 'str' object is not callable In [244]: me.age Out[244]: 18 In [245]: me[0] Out[245]: 'xxj' In [246]: me[2] --------------------------------------------------------------------------- IndexError Traceback (most recent call last) <ipython-input-246-4bc5e7d46893> in <module>() ----> 1 me[2] IndexError: tuple index out of range In [247]: me[0] = "xj" --------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-247-627de02ba5b9> in <module>() ----> 1 me[0] = "xj" TypeError: '_Yonghu' object does not support item assignment In [249]: type(namedtuple) Out[249]: function In [250]: type(User) Out[250]: type In [251]: type(me) Out[251]: __main__._Yonghu In [254]: print(namedtuple.__doc__) Returns a new subclass of tuple with named fields. >>> Point = namedtuple('Point', ['x', 'y']) >>> Point.__doc__ # docstring for the new class 'Point(x, y)' >>> p = Point(11, y=22) # instantiate with positional args or keywords >>> p[0] + p[1] # indexable like a plain tuple 33 >>> x, y = p # unpack like a regular tuple >>> x, y (11, 22) >>> p.x + p.y # fields also accessible by name 33 >>> d = p._asdict() # convert to a dictionary >>> d['x'] 11 >>> Point(**d) # convert from a dictionary Point(x=11, y=22) >>> p._replace(x=100) # _replace() is like str.replace() but targets named fields