# Python 2
input() # 等同 eval(raw_input()),輸入 1+1 回傳 int 2
raw_input()# 純字串
# Python 3
input() # 只有這個,行為等同 Py2 raw_input(),回傳 str
# raw_input() 不存在
遷移建議:Python 3 代碼統一用 input(),需數值時 int(input())、float(input())。
# 標準語法 (Python 2.5+)
value = true_val if condition else false_val
# 陣列技巧 (舊版相容)
value = (condition and [true_val] or [false_val])[0]
範例:
>> "成年" if age >= 18 else "未成年"
'成年'
>>> (age >= 18 and ["成年"] or ["未成年"])[0]
'成年'
def find_nth(haystack, needle, n):
parts = haystack.split(needle, n)
if len(parts) <= n:
return -1
return len(haystack) - len(parts[-1]) - len(needle)
s = "123(1)456(1)789(1)0"
print(find_nth(s, "(1)", 2)) # 14
print(find_nth(s, "(1)", 10)) # -1
>> for i, ch in enumerate("abc"):
... print(i, ch)
0 a
1 b
2 c
# 指定起始索引
>>> list(enumerate("xy", start=1))
[(1, 'x'), (2, 'y')]
>> import random
>>> lst = list(range(1, 11))
>>> random.sample(lst, 5)
[3, 7, 1, 9, 2] # 原列表不變
對比:random.choices(lst, k=5) 有放回抽樣(可能重複)。
>> import json
>>> data = {"msg": "你好世界"}
>>> print(json.dumps(data)) # 預設 ensure_ascii=True
{"msg": "\u4f60\u597d\u4e16\u754c"}
>>> print(json.dumps(data, ensure_ascii=False))
{"msg": "你好世界"}
dict.get(key, default) 避免 KeyError。collections.defaultdict(list) 自動初始化列表值。itertools.chain、islice、groupby 處理迭代器組合。__slots__ 限制實例屬性、節省記憶體。functools.lru_cache 遞迴函式記憶化。