記錄Python各種容易遺忘的段落
不同於Java,可以多重繼承。
Basic
int( … , 2)
將… 轉2為底的int合併
[1]+[1] == [1,1]zip
a, b = [1,2,3], [4,5,6]
print(list(zip(a,b)))[(1, 4), (2, 5), (3, 6)]
count += (sum(edges) >= 1)
True+True == 2賦值
x, y, d = q.popleft()
或 for a, b in (…)
pop 出來分給x,y,d- for i, j in enumerate(…)
[[i0, j0], [i1, j1], …]
- for i, j in enumerate(…)
copy
import random, copy
change = copy.deepcopy(self.nums)
random.shuffle(change)
在新生陣列打亂順序反轉
[::-1]if l < mid >r:
mid >l && rif mid < len(nums) -1 else float(‘-inf’)
inf@lru_cache(maxsize=None)
寫在def上方,暫存重用值,time() 或 random() 變動函數前沒有意義,maxsize 默認 128,如果 maxsize 設為 None,LRU 特性將被禁用且緩存可無限增長全域變數
global a,b
a,b = 1,2“”.join(sum(res, []))
[[1],[2],[3],[4]] => [1,2,3,4]拆包
1 | a = [[1],[2],[3],[4]] |
Loop
走訪陣列
for _ in range(n):走訪串列
fast = llst.head
while fast and fast.next:
fast = fast.nextfor(while):…else:
沒有在for中被break,順利執行完就跑else區塊取值
1 | def foo(param1, *param2): |
- Product 3X3
1 | from itertools import product |
- 從最長開始排序
1 | words = {"able","ale","apple","bale","kangaroo"} |
Comprehension
- … if … else …
if, else,沒有:
1 | age_group = "Minor" if age < 18 else "Adult" |
- … if … else … if … else …
if, elif, else,沒有:
1 | board[i][j] = 'X' if board[i][j] == 'O' else 'O' if board[i][j] == 'S' else board[i][j] |
- [int(i)**2 for i in str(n)]
從n取各值為i,轉int後平方再展開
function
1 | class Account: |
Assert
AssertionError: 印出失敗訊息,並不會進行後續動作
assert <條件>, <條件失敗訊息>
1 |
|
如果你覺得這篇文章很棒,請你不吝點讚 (゚∀゚)