Lunski's Clutter

This is a place to put my clutters, no matter you like it or not, welcome here.

0%

Python

記錄Python各種容易遺忘的段落

不同於Java,可以多重繼承。

Basic

  • 為了可讀性 1000與1_000一致

  • 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], …]
  • copy
    import random, copy
    change = copy.deepcopy(self.nums)
    random.shuffle(change)
    在新生陣列打亂順序

  • 反轉
    [::-1]

  • if l < mid >r:
    mid >l && r

  • if 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
2
3
4
5
6
7
8
9
a = [[1],[2],[3],[4]]
print(*a) # [1] [2] [3] [4]

a = [1,2,3]
print(*a) # 1,2,3

a = [[1,2,3],[4,5,6]]
print(*a) # [1,2,3],[4,5,6]

Loop

  • 走訪陣列
    for _ in range(n):

  • 走訪串列
    fast = llst.head
    while fast and fast.next:
    fast = fast.next

  • for(while):…else:
    沒有在for中被break,順利執行完就跑else區塊

  • 取值

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
def foo(param1, *param2):
print(param1)
print(param2)

def bar(param1, **param2):
print(param1)
print(param2)

foo(1,2,3,4,5)
bar(1,a=2,b=3)
>
1
(2, 3, 4, 5)
1
{'a': 2, 'b': 3}
  • Product 3X3
1
2
3
4
5
6
7
8
9
10
11
12
13
from itertools import product 
for i, j in product(range(0,3),range(0,3)):
print(i,j)
>
0 0
0 1
0 2
1 0
1 1
1 2
2 0
2 1
2 2
  • 從最長開始排序
1
2
3
4
5
6
7
8
9
words = {"able","ale","apple","bale","kangaroo"}
for word in sorted(words, key=len, reverse=True):
print(word)
>
kangaroo
apple
able
bale
ale

Comprehension

  • … if … else …
    if, else,沒有:
1
2
3
4
5
6
7
age_group = "Minor" if age < 18 else "Adult"
==

if age < 18:
age_group = "Minor"
else:
age_group = "Adult"
  • … if … else … if … else …
    if, elif, else,沒有:
1
2
3
4
5
6
7
8
9
board[i][j] = 'X' if board[i][j] == 'O' else 'O' if board[i][j] == 'S' else board[i][j] 
==

if board[i][j] == 'O':
board[i][j] = 'X'
elif board[i][j] == 'S':
board[i][j] = 'O'
else:
board[i][j]
  • [int(i)**2 for i in str(n)]
    從n取各值為i,轉int後平方再展開

function

1
2
3
4
5
6
7
8
9
class Account:
def __init__(self, number, name):
self.number = number
self.name = name
self.balance = 0
def deposit(self, amount):
...
a = Account('E122', 'Justin')
a.deposit(-1)

Assert

AssertionError: 印出失敗訊息,並不會進行後續動作

assert <條件>, <條件失敗訊息>

1
2
3
4
5
6
7
8
9

if x > 0:
# do some
...
else:
assert x == 0, 'x 不會是負數' # AssertionError: x 不會是負數
# do other
...


如果你覺得這篇文章很棒,請你不吝點讚 (゚∀゚)

Welcome to my other publishing channels