串列方法
- list.append(x):把一個元素添加到串列的結尾,相當于 a[len(a):] = [x],
- list.extend(L):通過添加指定串列的所有元素來擴充串列,相當于 a[len(a):] = L,
- list.insert(i, x):在指定位置插入一個元素,第一個引數是準備插入到其前面的那個元素的索引,例如 a.insert(0, x) 會插入到整個串列之前,而 a.insert(len(a), x) 相當于 a.append(x) ,
- list.remove(x):洗掉串列中值為 x 的第一個元素,如果沒有這樣的元素,就會回傳一個錯誤,
- list.pop([i]):從串列的指定位置移除元素,并將其回傳,如果沒有指定索引,a.pop()回傳最后一個元素,元素隨即從串列中被移除,(方法中 i 兩邊的方括號表示這個引數是可選的,而不是要求你輸入一對方括號,你會經常在 Python 庫參考手冊中遇到這樣的標記,)
- list.clear():移除串列中的所有項,等于del a[:],
- list.index(x):回傳串列中第一個值為 x 的元素的索引,如果沒有匹配的元素就會回傳一個錯誤,
- list.count(x):回傳 x 在串列中出現的次數,
- list.sort():對串列中的元素進行排序,
- list.reverse():倒排串列中的元素,
- list.copy():回傳串列的淺復制,等于a[:],
串列當堆疊使用
用 append() 方法可以把一個元素添加到堆疊頂,用不指定索引的 pop() 方法可以把一個元素從堆疊頂釋放出來,
串列當佇列使用
在佇列里第一加入的元素,第一個取出來;但是拿串列用作這樣的目的效率不高,在串列的最后添加或者彈出元素速度快,然而在串列里插入或者從頭部彈出速度卻不快(因為所有其他的元素都得一個一個地移動),
1 >>> from collections import deque 2 >>> queue = deque(["Eric", "John", "Michael"]) 3 >>> queue.append("Terry") # Terry arrives 4 >>> queue.append("Graham") # Graham arrives 5 >>> queue.popleft() # The first to arrive now leaves 6 'Eric' 7 >>> queue.popleft() # The second to arrive now leaves 8 'John' 9 >>> queue # Remaining queue in order of arrival 10 deque(['Michael', 'Terry', 'Graham'])
串列推導式
串列推導式提供了從序列創建串列的簡單途徑,每個串列推導式都在 for 之后跟一個運算式,然后有零到多個 for 或 if 子句,回傳結果是一個根據表達從其后的 for 和 if 背景關系環境中生成出來的串列,如果希望運算式推匯出一個元組,就必須使用括號,
可以對每一個元素逐個呼叫,Python strip() 方法用于移除字串頭尾指定的字符(默認為空格)或字符序列,
1 >>> freshfruit = [' banana', ' loganberry ', 'passion fruit '] 2 >>> [weapon.strip() for weapon in freshfruit] 3 ['banana', 'loganberry', 'passion fruit']
一些技巧,round() 方法回傳浮點數x的四舍五入值,round() 方法回傳浮點數x的四舍五入值,
- x -- 數值運算式,
- n -- 數值運算式,表示從小數點位數,
1 >>> [3*x for x in vec if x > 3] 2 [12, 18] 3 >>> [3*x for x in vec if x < 2] 4 [] 5 >>> [x*y for x in vec1 for y in vec2] 6 [8, 6, -18, 16, 12, -36, 24, 18, -54] 7 >>> [x+y for x in vec1 for y in vec2] 8 [6, 5, -7, 8, 7, -5, 10, 9, -3] 9 >>> [vec1[i]*vec2[i] for i in range(len(vec1))] 10 [8, 12, -54] 11 >>> [str(round(355/113, i)) for i in range(1, 6)] 12 ['3.1', '3.14', '3.142', '3.1416', '3.14159']
嵌套串列
>>> matrix = [ ... [1, 2, 3, 4], ... [5, 6, 7, 8], ... [9, 10, 11, 12], ... ] >>> [[row[i] for row in matrix] for i in range(4)] [[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]
>>> transposed = [] >>> for i in range(4): ... transposed.append([row[i] for row in matrix]) ... >>> transposed [[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]
>>> transposed = [] >>> for i in range(4): ... # the following 3 lines implement the nested listcomp ... transposed_row = [] ... for row in matrix: ... transposed_row.append(row[i]) ... transposed.append(transposed_row) ... >>> transposed [[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]
del陳述句
使用 del 陳述句可以從一個串列中依索引而不是值來洗掉一個元素,這與使用 pop() 回傳一個值不同,可以用 del 陳述句從串列中洗掉一個切割,或清空整個串列,
1 >>> a = [-1, 1, 66.25, 333, 333, 1234.5] 2 >>> del a[0] 3 >>> a 4 [1, 66.25, 333, 333, 1234.5] 5 >>> del a[2:4] 6 >>> a 7 [1, 66.25, 1234.5] 8 >>> del a[:] 9 >>> a 10 []
元組和序列
組在輸出時總是有括號的,以便于正確表達嵌套結構,在輸入時可能有或沒有括號, 不過括號通常是必須的,
集合
集合是一個無序不重復元素的集,基本功能包括關系測驗和消除重復元素,
可以用大括號({})創建集合,注意:如果要創建一個空集合,你必須用 set() 而不是 {} ;后者創建一個空的字典,
字典
序列是以連續的整數為索引,與此不同的是,字典以關鍵字為索引,關鍵字可以是任意不可變型別,通常用字串或數值,理解字典的最佳方式是把它看做無序的鍵=>值對集合,在同一個字典之內,關鍵字必須是互不相同,一對大括號創建一個空的字典:{},
建構式 dict() 直接從鍵值對元組串列中構建字典,如果有固定的模式,串列推導式指定特定的鍵值對:
>>> dict([('sape', 4139), ('guido', 4127), ('jack', 4098)]) {'sape': 4139, 'jack': 4098, 'guido': 4127}
字典推導可以用來創建任意鍵和值的運算式詞典
>>> {x: x**2 for x in (2, 4, 6)}
{2: 4, 4: 16, 6: 36}
如果關鍵字只是簡單的字串,使用關鍵字引數指定鍵值對有時候更方便
>>> dict(sape=4139, guido=4127, jack=4098) {'sape': 4139, 'jack': 4098, 'guido': 4127}
遍歷技巧
在字典中遍歷時,關鍵字和對應的值可以使用 items() 方法同時解讀出來
>>> knights = {'gallahad': 'the pure', 'robin': 'the brave'}
>>> for k, v in knights.items():
... print(k, v)
在序列中遍歷時,索引位置和對應值可以使用 enumerate() 函式同時得到
>>> for i, v in enumerate(['tic', 'tac', 'toe']): ... print(i, v) ... 0 tic 1 tac 2 toe
同時遍歷兩個或更多的序列,可以使用 zip() 組合
1 >>> questions = ['name', 'quest', 'favorite color'] 2 >>> answers = ['lancelot', 'the holy grail', 'blue'] 3 >>> for q, a in zip(questions, answers): 4 ... print('What is your {0}? It is {1}.'.format(q, a)) 5 ... 6 What is your name? It is lancelot. 7 What is your quest? It is the holy grail. 8 What is your favorite color? It is blue.
format格式化函式
print("網站名:{name}, 地址 {url}".format(name="菜鳥教程", url="www.runoob.com")) # 通過字典設定引數 site = {"name": "菜鳥教程", "url": "www.runoob.com"} print("網站名:{name}, 地址 {url}".format(**site)) # 通過串列索引設定引數 my_list = ['菜鳥教程', 'www.runoob.com'] print("網站名:{0[0]}, 地址 {0[1]}".format(my_list)) # "0" 是必須的
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/231754.html
標籤:Python
