萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

Python 易忽視知識點總結:input/raw_input、三元運算、enumerate、random.sample、json 中文輸出

1. input() vs raw_input() (Python 2 vs 3)

# 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())。

2. 三元運算子(條件表達式)

# 標準語法 (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]
'成年'

3. 尋找字串中第 N 次出現的索引

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

4. enumerate() 同時取得索引與值

>> for i, ch in enumerate("abc"):
...     print(i, ch)
0 a
1 b
2 c

# 指定起始索引
>>> list(enumerate("xy", start=1))
[(1, 'x'), (2, 'y')]

5. random.sample() 從列表隨機抽樣(不重複)

>> import random
>>> lst = list(range(1, 11))
>>> random.sample(lst, 5)
[3, 7, 1, 9, 2]  # 原列表不變

對比:random.choices(lst, k=5) 有放回抽樣(可能重複)。

6. json.dumps 正確輸出中文

>> import json
>>> data = {"msg": "你好世界"}
>>> print(json.dumps(data))              # 預設 ensure_ascii=True
{"msg": "\u4f60\u597d\u4e16\u754c"}
>>> print(json.dumps(data, ensure_ascii=False))
{"msg": "你好世界"}

7. 其它易忘細節

  • dict.get(key, default) 避免 KeyError。
  • collections.defaultdict(list) 自動初始化列表值。
  • itertools.chain、islice、groupby 處理迭代器組合。
  • __slots__ 限制實例屬性、節省記憶體。
  • functools.lru_cache 遞迴函式記憶化。
copyright © 萬盛學電腦網 all rights reserved