Python「內建函數」(built-in functions)就是不用 import,隨時可以直接呼叫的函數,像 print()、len()、range() 這些,都算。
map():對每個元素套用函數
語法:
map(function, iterable, *iterables)map() 會把函數套用到可迭代物件的每一個元素上,產生一個新的迭代器。nums = [1, 2, 3, 4, 5]
# 每個元素平方
squared = list(map(lambda x: x ** 2, nums))
print(squared) # [1, 4, 9, 16, 25]
# 每個元素乘以 10
times_ten = list(map(lambda x: x * 10, nums))
print(times_ten) # [10, 20, 30, 40, 50]搭配具名函數
除了 lambda,也可以傳入具名函數,包括內建函數。
# 搭配內建函數
words = ['hello', 'world', 'python']
upper_words = list(map(str.upper, words))
print(upper_words) # ['HELLO', 'WORLD', 'PYTHON']
# 字串轉整數
str_nums = ['1', '2', '3', '4']
int_nums = list(map(int, str_nums))
print(int_nums) # [1, 2, 3, 4]
# 搭配自訂函數
def add_tax(price):
return round(price * 1.05, 1)
prices = [100, 200, 350]
with_tax = list(map(add_tax, prices))
print(with_tax) # [105.0, 210.0, 367.5]多個可迭代物件
map() 可以同時接受多個可迭代物件,函數的參數數量要對應。以最短的為準。
a = [1, 2, 3]
b = [10, 20, 30]
# 兩個列表對應相加
result = list(map(lambda x, y: x + y, a, b))
print(result) # [11, 22, 33]
# 三個列表
c = [100, 200, 300]
result = list(map(lambda x, y, z: x + y + z, a, b, c))
print(result) # [111, 222, 333]map() vs 列表推導式
map() 和列表推導式都能做轉換,通常列表推導式更 Pythonic,但 map() 搭配已有函數時更簡潔。
nums = [1, 2, 3, 4, 5]
# map 寫法
squared_map = list(map(lambda x: x ** 2, nums))
# 列表推導式寫法
squared_comp = [x ** 2 for x in nums]
print(squared_map) # [1, 4, 9, 16, 25]
print(squared_comp) # [1, 4, 9, 16, 25]
# 搭配已有函數時 map 更簡潔
str_nums = ['1', '2', '3']
print(list(map(int, str_nums))) # [1, 2, 3]
print([int(x) for x in str_nums]) # [1, 2, 3]小小綜合例子
# 溫度轉換工具
celsius = [0, 10, 20, 25, 30, 37, 100]
# 攝氏轉華氏
def c_to_f(c):
return round(c * 9/5 + 32, 1)
# 攝氏轉開爾文
def c_to_k(c):
return round(c + 273.15, 2)
fahrenheit = list(map(c_to_f, celsius))
kelvin = list(map(c_to_k, celsius))
print('=== 溫度轉換表 ===')
print(f'{"攝氏":>6} {"華氏":>8} {"開爾文":>8}')
print('-' * 26)
for c, f, k in zip(celsius, fahrenheit, kelvin):
print(f'{c:>5}°C {f:>7}°F {k:>7}K')
# 找出體溫以上的溫度
hot = list(filter(lambda c: c >= 37, celsius))
print(f'\n高於體溫的有:{list(map(lambda c: f"{c}°C", hot))}')
# === 溫度轉換表 ===
# 攝氏 華氏 開爾文
# --------------------------
# 0°C 32.0°F 273.15K
# 10°C 50.0°F 283.15K
# 20°C 68.0°F 293.15K
# 25°C 77.0°F 298.15K
# 30°C 86.0°F 303.15K
# 37°C 98.6°F 310.15K
# 100°C 212.0°F 373.15K
#
# 高於體溫的有:['37°C', '100°C']