Python中map函数的解释和可视化

简介: Python中map函数的解释和可视化

先重温一下迭代(Iteration)、迭代器对象(iterable)、迭代器(iterator )的概念:

Iteration是计算机科学的通用术语,它是指对一组元素执行一项操作,一次执行一个元素。一个很好的例子是循环 - 它适用于每个单独的项目,直到整个项目集运行完毕为止。


Iterable是可以遍历的对象(译者注:在Python中所有东西都是object, 比如说变量,容器,类),iterable是可以产生iterator的object。


iterator是表示数据流的对象,它一次返回一个元素的数据。它还会记住其在迭代过程中的位置。本质上,它控制应如何迭代可迭代对象。


map()的用法


map()函数以迭代的方式将提供的功能应用于每个项目,结果是作为迭代器的map对象。语法:


map(func, *iterables)


如果没有map(),我们将不得不编写复杂的代码以在多个项目上“循环”给定的函数。以一个整洁的小实验为例:我们有一个10个单词的列表。


test_list = ["effort", "circle", "yearly", "woolen", "accept", "lurker",
            "island", "faucet", "glossy", "evader"]


我们怀疑其中一些可能是abcderian(按字母顺序出现的)。我们编写一个函数is_abecedarian来检查给定的单词是否为abcderian:


def is_abecedarian(input_word):
    index = 0
    for letter in input_word[0:-1]:
        if ord(input_word[index]) > ord(input_word[index + 1]):
            return False
        else:
            index += 1
    return True


现在,我们想将函数应用于单词列表,并创建一个将包含True和False值的新列表,以表明某些单词是否确实是abcderian。


下面方法涉及初始化一个新列表,然后使用for循环遍历列表元素:


value_list = []
for item in test_list:
    value = is_abecedarian(item)
    value_list.append(value)


输出:


[True, False, False, False, True, False, False, False, True, False]


如果用map(),我们可以将上面的代码简化为一个简洁的小代码:


map(is_abecedarian, test_list)


请注意map()不会返回列表,而是返回一个map对象。


译者注:map()函数在python2中返回的是列表。


你可能很好奇哪个词实际上是abcderian的字母-让我们编写这个问题的答案:


for item in test_list:
    if is_abecedarian(item):
        print(f"The word '{item}' is abecedarian. :)")
    else:
        print(f"The word '{item}' is not abecedarian. (")


输出:


The word 'effort' is abecedarian. :)
The word 'circle' is not abecedarian.
The word 'yearly' is not abecedarian.
The word 'woolen' is not abecedarian.
The word 'accept' is abecedarian. :)
The word 'lurker' is not abecedarian.
The word 'island' is not abecedarian.
The word 'faucet' is not abecedarian.
The word 'glossy' is abecedarian. :)
The word 'evader' is not abecedarian.


我们还可以用可视化的方式形象地解释,以帮助您更好地理解它:

640.png

这张图也有助于定义 map 和mapping-我们可以使用Allen B. Downey在他的《Think Python》书中提供的定义:


映射操作(map):一种遍历一个序列并对每个元素执行操作的处理模式。


映射(mapping):一个集合中的每个元素对应另一个集合中的一个元素的关系


将map()转换为列表,元组和集合


由于map()不返回列表/元组/集合,因此我们需要采取额外的步骤来转换生成的map对象:


def capitalize_word(input_word):
    return input_word.capitalize()
map_object = map(capitalize_word, ['strength', 'agility', 'intelligence'])
test_list = list(map_object)
print(test_list)
map_object = map(capitalize_word, ['health', 'mana', 'gold'])
test_set = set(map_object)
print(test_set)
map_object = map(capitalize_word, ['armor', 'weapon', 'spell'])
test_tuple = tuple(map_object)
print(test_tuple)


输出:


['Strength', 'Agility', 'Intelligence']
{'Mana', 'Health', 'Gold'}
('Armor', 'Weapon', 'Spell')


将map()与Lambda表达式结合

640.png

Lambda表达式是对我们的工具库的一个很好的补充:将Lambda表达式与map()代码相结合可使您的Python程序更小,更精确。


Lambda表达式可以创建匿名函数,即未约定特定标识符的函数。相反,通过def关键字创建函数会将函数绑定到其唯一标识符(例如def my_function创建标识符my_function)。


但是,lambda表达式也有一系列限制:它们每个只能做一件事情,只能在一个地方使用,通常与其他功能结合使用。我们看看lambda表达式如何map()同时使用:


cities = ["caracas", "bern", "oslo", "ottawa", "bangkok"]
def capitalize_word(input_word):
    return input_word.capitalize()
capitalized_cities = map(capitalize_word, cities)


更简洁的版本:


cities = ["caracas", "bern", "oslo", "ottawa", "bangkok"]
capitalized_cities = map(lambda s: s.capitalize(), cities)


需要注意:map()和lambda表达式提供了凝聚多行代码成一行的能力。尽管此功能非常出色,但我们需要牢记编程的黄金法则之一:代码读取比写入更频繁。这意味着map()和lambda表达式都可以提高代码的简洁性,但是却牺牲了代码的清晰度。遗憾的是,

对于代码的可读性,实际上并没有明确的指导方针- 随着编程经验的增长,大家将逐渐明白这一点。


使用map()遍历字典


map()也非常适合遍历字典


假设有一个包含苹果,梨和樱桃价格的字典,我们需要通过应用15%的折扣来更新价格表。方法如下:


price_list = {
    "pear": 0.60,
    "cherries": 0.90,
    "apple": 0.35,
}
def calulates_discount(item_price):
    return (item_price[0], round(item_price[1] * 0.85, 2))
new_price_list = dict(map(calulates_discount, price_list.items()))


输出:


{'pear': 0.51, 'cherries': 0.77, 'apple': 0.3}


将map()与Lambda表达式组合遍历字典


当开始组合多个功能时,编程特别有趣,一个很好的例子是map()配合使用和lambda表达式来遍历字典。在下面的代码中,我们初始化字典列表,并将每个字典作为参数传递给lambda函数。


list_of_ds = [{'user': 'Jane', 'posts': 18}, {'user': 'Amina', 'posts': 64}]
map(lambda x: x['user'], list_of_ds)  # Output: ['Jane', 'Amina']
map(lambda x: x['posts'] * 10, list_of_ds)  # Output: [180, 640]
map(lambda x: x['user'] == "Jane", list_of_ds)  # Output: [True, False]


map()替代方法:列表解析


像所有技术/产品/方法等等一样,一些Python开发人员认为map()函数在某种程度上不是Python风格(即未遵循应如何构建Python程序的精神和设计理念)。他们建议改用列表解析,比如:


map(f, iterable)


变成


[f(x) for x in iterable]


在速度和性能方面,map()与列表理析大致相等,因此不可能看到执行时间显着减少 - 经验丰富的Python开发者Wesley Chun在其演讲<Python 103:Memory Model&Best Practices>中解决了这个问题,

相关文章
|
2天前
|
Serverless 数据处理 数据库
Python函数的多返回值详解
Python函数的多返回值详解
6 1
|
2天前
|
数据处理 Python
Python函数:深入理解与应用
Python函数:深入理解与应用
6 1
|
2天前
|
算法 Python
Python函数的嵌套调用:深入理解与应用
Python函数的嵌套调用:深入理解与应用
9 1
|
2天前
|
IDE 开发工具 开发者
Python函数说明文档:编写清晰易懂的文档字符串
Python函数说明文档:编写清晰易懂的文档字符串
7 1
|
2天前
|
Python
Python函数的返回值深入解析
Python函数的返回值深入解析
7 1
|
2天前
|
存储 Python
Python函数参数详解
Python函数参数详解
8 1
|
3天前
|
Python
Python中的函数
Python中的函数
|
3天前
|
Python
Python 内置函数
Python 内置函数
|
3天前
|
自然语言处理 Python
Python 函数
Python 函数
|
3天前
|
Python
Python函数式编程自带函数
Python函数式编程自带函数
6 1