了解地图功能 [英] Understanding the map function

查看:63
本文介绍了了解地图功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

map(function, iterable, ...)

将函数应用于可迭代的每个项目并返回结果列表.如果传递了额外的可迭代参数,则函数必须采用那么多参数并并行应用于所有可迭代项中的项目.

Apply function to every item of iterable and return a list of the results. If additional iterable arguments are passed, function must take that many arguments and is applied to the items from all iterables in parallel.

如果一个迭代比另一个更短,则假定用 None 项进行扩展.

If one iterable is shorter than another it is assumed to be extended with None items.

如果函数为None,则假定为恒等函数;如果有多个参数,map() 返回一个由元组组成的列表,其中包含来自所有可迭代对象的相应项(一种转置操作).

If function is None, the identity function is assumed; if there are multiple arguments, map() returns a list consisting of tuples containing the corresponding items from all iterables (a kind of transpose operation).

可迭代参数可以是序列或任何可迭代对象;结果总是一个列表.

The iterable arguments may be a sequence or any iterable object; the result is always a list.

这在制作笛卡尔积中起什么作用?

What role does this play in making a Cartesian product?

content = map(tuple, array)

将元组放在其中的任何位置有什么影响?我还注意到,如果没有 map 函数,输出是 abc,有了它,它就是 a, b, c.

What effect does putting a tuple anywhere in there have? I also noticed that without the map function the output is abc and with it, it's a, b, c.

我想完全理解这个功能.参考定义也很难理解.太多花哨的绒毛.

I want to fully understand this function. The reference definitions is also hard to understand. Too much fancy fluff.

推荐答案

map 并不是特别 Pythonic.我建议改用列表推导式:

map isn't particularly pythonic. I would recommend using list comprehensions instead:

map(f, iterable)

基本上等价于:

[f(x) for x in iterable]

map 本身不能做笛卡尔积,因为它的输出列表的长度总是与其输入列表的长度相同.不过,您可以使用列表推导式轻松完成笛卡尔积:

map on its own can't do a Cartesian product, because the length of its output list is always the same as its input list. You can trivially do a Cartesian product with a list comprehension though:

[(a, b) for a in iterable_a for b in iterable_b]

语法有点混乱——基本上等同于:

The syntax is a little confusing -- that's basically equivalent to:

result = []
for a in iterable_a:
    for b in iterable_b:
        result.append((a, b))

这篇关于了解地图功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆