map()
- map() 函数将指定的函数应用于可迭代对象(如列表或元组)中的每个项目,并返回结果的迭代器。
- 它可用于高效转换数据,而无需显式循环。
语法:
map(function, iterable, ...)
示例:假设您有一个价格列表(以美元为单位),并且您希望将它们转换为美分。这里有四种不同的方法可以做到这一点。
- 不使用map (使用 For 循环)
prices_in_dollars = [10.99, 5.50, 3.75, 20.00]
# Function to convert dollars to cents
def dollars_to_cents(price):
return int(price * 100)
# Using a for loop to apply the function to each price
prices_in_cents = []
for price in prices_in_dollars:
cents = dollars_to_cents(price)
prices_in_cents.append(cents)
print(prices_in_cents)
# Output: [1099, 550, 375, 2000]
2. 使用 map 和 Function(不带 Lambda)
prices_in_dollars = [10.99, 5.50, 3.75, 20.00]
# Function to convert dollars to cents
def dollars_to_cents(price):
return int(price * 100)
# Using map to apply the function to each price
prices_in_cents = list(map(dollars_to_cents, prices_in_dollars))
print(prices_in_cents)
# Output: [1099, 550, 375, 2000]
3. 使用 map 和 Lambda 函数
以下是修改为使用 lambda 函数的代码,而不是定义用于将美元转换为美分的单独函数。
# List of prices in dollars
prices_in_dollars = [10.99, 5.50, 3.75, 20.00]
# Using map with a lambda function
prices_in_cents = list(map(lambda price: int(price * 100), prices_in_dollars))
print(prices_in_cents)
# Output: [1099, 550, 375, 2000]
4. 列表推导式
下面是在列表推导式中使用 lambda 函数而不是单独函数的代码:
prices_in_dollars = [10.99, 5.50, 3.75, 20.00]
# Using list comprehension with a lambda function
prices_in_cents = [(lambda price: int(price * 100))(price) for price in prices_in_dollars]
print(prices_in_cents)
# Output: [1099, 550, 375, 2000]