使用 enumerate 進行 iteration
好的程式碼:
fruits = ['orange', 'grape', 'pitaya', 'blueberry'] for index, fruit in enumerate(fruits): print(index, ':', fruit)
不好的程式碼:
fruits = ['orange', 'grape', 'pitaya', 'blueberry'] index = 0 for fruit in fruits: print(index, ':', fruit) index += 1
用生成式生成列表
好的程式碼:
data = [7, 20, 3, 15, 11] result = [num * 3 for num in data if num > 10] print(result) # [60, 45, 33]
不好的程式碼:
data = [7, 20, 3, 15, 11] result = [] for i in data: if i > 10: result.append(i * 3) print(result) # [60, 45, 33]
用 zip 創建字典: 組合 key 和 value
好的程式碼:
keys = ['1001', '1002', '1003'] values = ['第一組', '第二組', '第三組'] d = dict(zip(keys, values)) print(d)
不好的程式碼:
keys = ['1001', '1002', '1003'] values = ['第一組', '第二組', '第三組'] d = {} for i, key in enumerate(keys): d[key] = values[i] print(d)