介绍
在本教程中,我们将探讨如何使用 lambda 函数来更新 Python 字典中的值。Lambda 函数是紧凑的匿名函数,在使用字典时,可以使你的代码更简洁、更易读。通过本指南,你将了解如何使用这些强大的工具来简化 Python 程序中的字典操作。
Lambda 函数入门
在这一步中,我们将学习什么是 lambda 函数以及如何在 Python 中创建它们。
什么是 Lambda 函数?
Lambda 函数是一个小的匿名函数,使用 lambda 关键字定义。与使用 def 关键字声明的常规函数不同,lambda 函数可以写在一行中,并且不需要名称。它们非常适合你需要快速执行的简单操作。
lambda 函数的基本语法是:
lambda arguments: expression
这里,arguments 是函数的输入,而 expression 是产生结果的操作。
创建你的第一个 Lambda 函数
让我们创建一个简单的 lambda 函数,看看它是如何工作的。通过单击顶部菜单栏中的“File” > “New File”,在代码编辑器中打开一个新的 Python 文件。将文件命名为 lambda_basics.py 并将其保存在 /home/labex/project 目录中。
将以下代码添加到文件中:
## Define a regular function
def add_numbers(x, y):
return x + y
## Same function as a lambda
add_lambda = lambda x, y: x + y
## Test both functions
print("Regular function result:", add_numbers(5, 3))
print("Lambda function result:", add_lambda(5, 3))
通过打开终端(如果尚未打开)并执行以下命令来运行代码:
python3 lambda_basics.py
你应该看到以下输出:
Regular function result: 8
Lambda function result: 8
这两个函数执行相同的操作,但 lambda 版本更简洁。
何时使用 Lambda 函数
Lambda 函数在以下情况下最有用:
- 你需要一个简单的函数,用于短时间
- 你想将一个函数作为参数传递给另一个函数
- 你需要对集合中的项目应用一个简单的操作
让我们看另一个例子。将以下代码添加到你的 lambda_basics.py 文件中:
## Using lambda with built-in functions
numbers = [1, 2, 3, 4, 5]
## Square each number using lambda
squared = list(map(lambda x: x**2, numbers))
## Filter even numbers using lambda
evens = list(filter(lambda x: x % 2 == 0, numbers))
print("Original numbers:", numbers)
print("Squared numbers:", squared)
print("Even numbers:", evens)
再次运行该文件:
python3 lambda_basics.py
输出现在将包括:
Original numbers: [1, 2, 3, 4, 5]
Squared numbers: [1, 4, 9, 16, 25]
Even numbers: [2, 4]
在这个例子中,我们使用 lambda 函数与 map 和 filter 内置函数来转换和过滤数字列表。当我们在下一步中使用字典时,这类操作将非常有用。
理解 Python 中的字典
在使用 lambda 函数处理字典之前,让我们确保你理解 Python 中字典的工作方式。
什么是字典?
字典是键值对的集合。每个键都与一个值相关联,当你知道键时,可以快速访问值。字典是可变的,这意味着你可以在创建字典后更改、添加或删除项目。
创建和访问字典
让我们在 /home/labex/project 目录中创建一个名为 dictionary_basics.py 的新文件,并添加以下代码:
## Creating a dictionary
product_prices = {
'apple': 1.50,
'banana': 0.75,
'orange': 1.20,
'grapes': 2.50
}
## Accessing dictionary values
print("Price of apple:", product_prices['apple'])
## Adding a new item
product_prices['watermelon'] = 3.75
print("Updated dictionary:", product_prices)
## Modifying an existing item
product_prices['banana'] = 0.85
print("After modification:", product_prices)
## Iterating through a dictionary
print("\nAll products and their prices:")
for product, price in product_prices.items():
print(f"{product}: ${price:.2f}")
运行该文件:
python3 dictionary_basics.py
你应该看到类似于以下的输出:
Price of apple: 1.5
Updated dictionary: {'apple': 1.5, 'banana': 0.85, 'orange': 1.2, 'grapes': 2.5, 'watermelon': 3.75}
After modification: {'apple': 1.5, 'banana': 0.85, 'orange': 1.2, 'grapes': 2.5, 'watermelon': 3.75}
All products and their prices:
apple: $1.50
banana: $0.85
orange: $1.20
grapes: $2.50
watermelon: $3.75
使用字典方法
字典有几个有用的方法。让我们将以下代码添加到我们的 dictionary_basics.py 文件中:
## Dictionary methods
print("\nDictionary Methods:")
print("Keys:", list(product_prices.keys()))
print("Values:", list(product_prices.values()))
print("Items:", list(product_prices.items()))
## Check if a key exists
if 'apple' in product_prices:
print("Apple is in the dictionary")
## Get a value with a default if key doesn't exist
price = product_prices.get('pineapple', 'Not available')
print("Price of pineapple:", price)
再次运行该文件:
python3 dictionary_basics.py
你应该看到额外的输出:
Dictionary Methods:
Keys: ['apple', 'banana', 'orange', 'grapes', 'watermelon']
Values: [1.5, 0.85, 1.2, 2.5, 3.75]
Items: [('apple', 1.5), ('banana', 0.85), ('orange', 1.2), ('grapes', 2.5), ('watermelon', 3.75)]
Apple is in the dictionary
Price of pineapple: Not available
现在我们已经理解了 lambda 函数和字典,我们准备在下一步中将它们结合起来。
使用 Lambda 函数更新字典值
现在我们已经理解了 lambda 函数和字典,让我们看看如何使用 lambda 函数来更新字典值。
使用 Lambda 进行基本的字典更新
让我们在 /home/labex/project 目录中创建一个名为 update_dictionaries.py 的新文件,并添加以下代码:
## Create a dictionary of product prices
prices = {
'apple': 1.50,
'banana': 0.75,
'orange': 1.20,
'grapes': 2.50
}
print("Original prices:", prices)
## Apply a 10% discount to all prices using lambda and dictionary comprehension
discounted_prices = {item: round(price * 0.9, 2) for item, price in prices.items()}
print("Prices after 10% discount:", discounted_prices)
## Another way: using map() and lambda
## First, let's create a function that applies the map
def apply_to_dict(func, dictionary):
return dict(map(func, dictionary.items()))
## Now apply a 20% increase using the function and lambda
increased_prices = apply_to_dict(lambda item: (item[0], round(item[1] * 1.2, 2)), prices)
print("Prices after 20% increase:", increased_prices)
运行该文件:
python3 update_dictionaries.py
你应该看到类似于以下的输出:
Original prices: {'apple': 1.5, 'banana': 0.75, 'orange': 1.2, 'grapes': 2.5}
Prices after 10% discount: {'apple': 1.35, 'banana': 0.68, 'orange': 1.08, 'grapes': 2.25}
Prices after 20% increase: {'apple': 1.8, 'banana': 0.9, 'orange': 1.44, 'grapes': 3.0}
让我们分解一下发生了什么:
- 我们创建了一个产品价格的字典。
- 我们使用字典推导式(dictionary comprehension)和一个简单的计算来应用 10% 的折扣。
- 我们创建了一个辅助函数
apply_to_dict,它使用map()并将结果转换回字典。 - 我们使用这个函数和 lambda 来应用 20% 的价格上涨。
使用 Lambda 函数进行条件更新
现在,让我们有条件地更新我们的字典值。将以下代码添加到你的 update_dictionaries.py 文件中:
print("\n--- Conditional Updates ---")
## Apply different discounts: 15% for items over $1.00, 5% for the rest
varied_discount = {
item: round(price * 0.85, 2) if price > 1.00 else round(price * 0.95, 2)
for item, price in prices.items()
}
print("Varied discounts:", varied_discount)
## Using filter and lambda to update only certain items
def update_filtered_items(dictionary, filter_func, update_func):
## First, filter the items
filtered = dict(filter(filter_func, dictionary.items()))
## Then, update the filtered items
updated = {key: update_func(value) for key, value in filtered.items()}
## Merge with the original dictionary (only updating filtered items)
result = dictionary.copy()
result.update(updated)
return result
## Apply a 50% discount only to fruits starting with 'a'
special_discount = update_filtered_items(
prices,
lambda item: item[0].startswith('a'),
lambda price: round(price * 0.5, 2)
)
print("Special discount on items starting with 'a':", special_discount)
再次运行该文件:
python3 update_dictionaries.py
你现在应该看到额外的输出:
--- Conditional Updates ---
Varied discounts: {'apple': 1.28, 'banana': 0.71, 'orange': 1.02, 'grapes': 2.12}
Special discount on items starting with 'a': {'apple': 0.75, 'banana': 0.75, 'orange': 1.2, 'grapes': 2.5}
在这个例子中:
- 我们使用字典推导式中的条件表达式,根据价格应用不同的折扣百分比。
- 我们创建了一个函数,该函数使用 lambda 函数过滤项目,然后使用另一个 lambda 函数仅更新过滤后的项目。
- 我们应用了这个函数,仅对以字母 'a' 开头的商品提供 50% 的折扣。
这些例子展示了 lambda 函数如何使字典更新更简洁和可读,尤其是在与 Python 的内置函数(如 map() 和 filter())结合使用时。
高级应用:排序和转换字典
让我们探索一些使用 lambda 函数处理字典的更高级应用,重点关注排序和转换字典数据。
使用 Lambda 函数排序字典
Python 中的字典默认情况下是无序的,但有时我们需要以特定顺序处理它们。让我们在 /home/labex/project 目录中创建一个名为 advanced_dictionary_ops.py 的新文件,并添加以下代码:
## Create a dictionary of student scores
student_scores = {
'Alice': 92,
'Bob': 85,
'Charlie': 78,
'David': 95,
'Eva': 88
}
print("Original student scores:", student_scores)
## Sort by student names (keys)
sorted_by_name = dict(sorted(student_scores.items()))
print("\nSorted by name:", sorted_by_name)
## Sort by scores (values) in ascending order
sorted_by_score_asc = dict(sorted(student_scores.items(), key=lambda item: item[1]))
print("\nSorted by score (ascending):", sorted_by_score_asc)
## Sort by scores (values) in descending order
sorted_by_score_desc = dict(sorted(student_scores.items(), key=lambda item: item[1], reverse=True))
print("\nSorted by score (descending):", sorted_by_score_desc)
## Get the top 3 students by score
top_3_students = dict(sorted(student_scores.items(), key=lambda item: item[1], reverse=True)[:3])
print("\nTop 3 students:", top_3_students)
运行该文件:
python3 advanced_dictionary_ops.py
你应该看到类似于以下的输出:
Original student scores: {'Alice': 92, 'Bob': 85, 'Charlie': 78, 'David': 95, 'Eva': 88}
Sorted by name: {'Alice': 92, 'Bob': 85, 'Charlie': 78, 'David': 95, 'Eva': 88}
Sorted by score (ascending): {'Charlie': 78, 'Bob': 85, 'Eva': 88, 'Alice': 92, 'David': 95}
Sorted by score (descending): {'David': 95, 'Alice': 92, 'Eva': 88, 'Bob': 85, 'Charlie': 78}
Top 3 students: {'David': 95, 'Alice': 92, 'Eva': 88}
在这个例子中,我们使用 sorted() 函数和 lambda 函数以不同的方式对字典进行排序:
- 按键(学生姓名)
- 按值(分数),升序
- 按值(分数),降序
我们还使用了切片 [:3] 来仅获取排序后的前 3 名学生。
转换字典值
现在,让我们看看如何转换字典中的值。将以下代码添加到你的 advanced_dictionary_ops.py 文件中:
print("\n--- Transforming Dictionary Values ---")
## Create a dictionary of temperatures in Celsius
celsius_temps = {
'New York': 21,
'London': 18,
'Tokyo': 26,
'Sydney': 22,
'Moscow': 14
}
print("Temperatures in Celsius:", celsius_temps)
## Convert Celsius to Fahrenheit: F = C * 9/5 + 32
fahrenheit_temps = {city: round(temp * 9/5 + 32, 1) for city, temp in celsius_temps.items()}
print("Temperatures in Fahrenheit:", fahrenheit_temps)
## Categorize temperatures as cool, moderate, or warm
def categorize_temp(temp):
if temp < 18:
return "Cool"
elif temp < 25:
return "Moderate"
else:
return "Warm"
categorized_temps = {city: categorize_temp(temp) for city, temp in celsius_temps.items()}
print("Categorized temperatures:", categorized_temps)
## Group cities by temperature category using a lambda and reduce
from collections import defaultdict
from functools import reduce
grouped_cities = reduce(
lambda result, item: result[categorize_temp(item[1])].append(item[0]) or result,
celsius_temps.items(),
defaultdict(list)
)
print("\nCities grouped by temperature category:")
for category, cities in grouped_cities.items():
print(f"{category}: {', '.join(cities)}")
再次运行该文件:
python3 advanced_dictionary_ops.py
你现在应该看到额外的输出:
--- Transforming Dictionary Values ---
Temperatures in Celsius: {'New York': 21, 'London': 18, 'Tokyo': 26, 'Sydney': 22, 'Moscow': 14}
Temperatures in Fahrenheit: {'New York': 69.8, 'London': 64.4, 'Tokyo': 78.8, 'Sydney': 71.6, 'Moscow': 57.2}
Categorized temperatures: {'New York': 'Moderate', 'London': 'Moderate', 'Tokyo': 'Warm', 'Sydney': 'Moderate', 'Moscow': 'Cool'}
Cities grouped by temperature category:
Cool: Moscow
Moderate: New York, London, Sydney
Warm: Tokyo
在这个例子中:
- 我们使用字典推导式将摄氏温度转换为华氏温度。
- 我们使用一个辅助函数将温度分类为“Cool”、“Moderate”或“Warm”。
- 我们使用
reduce()函数和 lambda 将城市按温度类别分组。
这些技术展示了 lambda 函数如何使复杂的字典操作更简洁和可读。正如你所看到的,将 lambda 函数与 Python 的内置函数和字典操作相结合,为数据操作提供了强大的工具。
总结
在本教程中,你已经学习了如何使用 lambda 函数来更新 Python 中的字典值。我们涵盖了:
- 理解 lambda 函数及其语法
- 在 Python 中使用字典
- 使用 lambda 函数有条件和无条件地更新字典值
- 高级应用,例如排序字典和转换值
- 将 lambda 函数与 Python 的内置函数(如
map()、filter()和reduce())结合使用
这些技术将帮助你编写更简洁、更易读的代码,尤其是在使用 Python 中的字典时。随着你继续你的 Python 之旅,你会发现 lambda 函数将成为你编程工具包中越来越有价值的工具,尤其是在数据操作任务中。
请记住,虽然 lambda 函数很强大,但它们最适合简单的操作。对于更复杂的逻辑,请考虑使用常规的命名函数来保持代码的可读性和可维护性。



