跳至正文

高级函数

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) # ['李明', '王华']

[其余内容同样翻译,并保留代码块]