進階函式
Lambda 函式深入
map() 函式
# 基本使用
numbers = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x ** 2, numbers))
print(squared) # [1, 4, 9, 16, 25]
# 與一般函式比較
def square(x):
return x ** 2
squared2 = list(map(square, numbers))
print(squared2) # [1, 4, 9, 16, 25]
# 多個引數
def add(x, y):
return x + y
a = [1, 2, 3]
b = [10, 20, 30]
result = list(map(add, a, b))
print(result) # [11, 22, 33]
# 使用 Lambda
result2 = list(map(lambda x, y: x + y, a, b))
print(result2) # [11, 22, 33]
# 實用範例
prices = [100, 200, 300, 400]
with_tax = list(map(lambda x: x * 1.1, prices))
print(with_tax) # [110.0, 220.0, 330.0, 440.0]
# 字串處理
names = ["alice", "bob", "charlie"]
upper_names = list(map(str.upper, names))
print(upper_names) # ['ALICE', 'BOB', 'CHARLIE']
# 複雜轉換
users = [
{"name": "陳小姐", "age": 25},
{"name": "張先生", "age": 30}
]
names_only = list(map(lambda u: u["name"], users))
print(names_only) # ['陳小姐', '張先生']
[其餘內容同樣翻譯,並保留程式碼區塊]