06 - Python 速查表

05-常用模組 | 回到 → 00-Index


基本語法

# 變數與型別
x = 10; s = "hello"; f = 3.14; b = True
type(x)          # <class 'int'>
isinstance(x, int)  # True
 
# 輸入輸出
print("hello", end="")    # 不換行
name = input("名字:")    # 等待輸入

資料型態速查

# List
lst = [1, 2, 3]
lst.append(4)        # 加到末尾
lst.pop()            # 刪除末尾
lst.insert(0, 0)     # 插入到索引 0
lst.sort()           # 排序(in-place)
sorted(lst)          # 回傳新 list
len(lst)             # 長度
lst[::-1]            # 反轉
 
# Dict
d = {"a": 1}
d.get("b", 0)        # 取值,預設 0
d.keys()             # 所有 key
d.values()           # 所有 value
d.items()            # (key, value) 對
"a" in d             # 檢查 key 是否存在
 
# String
s = "hello world"
s.split(" ")         # ['hello', 'world']
" ".join(["a","b"])  # 'a b'
s.strip()            # 去除首尾空白
s.replace("l","L")   # 替換
s.startswith("h")    # True
f"{s!r}"             # repr 格式

控制流程速查

# if
x = 5
result = "big" if x > 3 else "small"
 
# for
[x**2 for x in range(10) if x % 2 == 0]   # list comprehension
{k: v for k, v in d.items()}               # dict comprehension
 
# 常用迭代工具
for i, val in enumerate(lst):    # 同時取 index
for a, b in zip(lst1, lst2):    # 同時遍歷兩個

函式速查

def func(a, b=10, *args, **kwargs):
    return a + b
 
lambda x: x ** 2               # 匿名函式
map(func, lst)                  # 對每個元素套用函式
filter(lambda x: x>0, lst)     # 篩選

檔案操作

# 讀檔
with open("file.txt", "r", encoding="utf-8") as f:
    content = f.read()         # 全部讀入
    lines = f.readlines()      # 按行讀入 list
 
# 寫檔
with open("file.txt", "w", encoding="utf-8") as f:
    f.write("hello\n")
 
# 附加寫入
with open("file.txt", "a", encoding="utf-8") as f:
    f.write("more content\n")

例外處理

try:
    result = 10 / 0
except ZeroDivisionError as e:
    print(f"錯誤:{e}")
except (TypeError, ValueError):
    print("型別或值錯誤")
finally:
    print("一定會執行")
 
# 主動拋出例外
raise ValueError("這是錯誤訊息")

實用內建函式

abs(-5)           # 5
max([1,2,3])      # 3
min([1,2,3])      # 1
sum([1,2,3])      # 6
sorted([3,1,2])   # [1,2,3]
reversed([1,2,3]) # 反轉迭代器
zip([1,2],[3,4])  # [(1,3),(2,4)]
enumerate([a,b])  # [(0,a),(1,b)]
any([F,T,F])      # True(任一為真)
all([T,T,T])      # True(全部為真)

05-常用模組 | 回到 → 00-Index