了解地图功能

本文翻译自:Understanding the map function

map(function, iterable, ...)

Apply function to every item of iterable and return a list of the results. 将函数应用于每个iterable项目,并返回结果列表。 If additional iterable arguments are passed, function must take that many arguments and is applied to the items from all iterables in parallel. 如果传递了其他可迭代参数,则函数必须采用那么多参数,并且并行地将其应用于所有可迭代对象的项。

If one iterable is shorter than another it is assumed to be extended with None items. 如果一个可迭代项比另一个可迭代项短,则假定它使用None项目扩展。

If function is None , the identity function is assumed; 如果function为None ,则假定身份函数; if there are multiple arguments, map() returns a list consisting of tuples containing the corresponding items from all iterables (a kind of transpose operation). 如果有多个参数,则map()返回一个包含元组的列表,该元组包含所有可迭代对象中的对应项(一种转置操作)。

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)

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 . 我还注意到,没有map函数,输出为abc ,输出为a, b, c

I want to fully understand this function. 我想完全了解此功能。 The reference definitions is also hard to understand. 参考定义也很难理解。 Too much fancy fluff. 花哨的绒毛太多。


#1楼

参考:https://stackoom.com/question/K2Me/了解地图功能


#2楼

map doesn't relate to a Cartesian product at all, although I imagine someone well versed in functional programming could come up with some impossible to understand way of generating a one using map . map根本与笛卡尔积无关,尽管我想象一个精通函数式编程的人会想出一些无法理解的方法来使用map生成一个。

map in Python 3 is equivalent to this: Python 3中的map等效于此:

def map(func, iterable):
    for i in iterable:
        yield func(i)

and the only difference in Python 2 is that it will build up a full list of results to return all at once instead of yield ing. Python 2的唯一区别是它将建立完整的结果列表以立即返回所有结果,而不是yield

Although Python convention usually prefers list comprehensions (or generator expressions) to achieve the same result as a call to map , particularly if you're using a lambda expression as the first argument: 尽管Python约定通常更喜欢列表推导(或生成器表达式)来实现与map调用相同的结果,尤其是如果您使用lambda表达式作为第一个参数:

[func(i) for i in iterable]

As an example of what you asked for in the comments on the question - "turn a string into an array", by 'array' you probably want either a tuple or a list (both of them behave a little like arrays from other languages) - 作为您在问题注释中要求的示例(“将字符串转换为数组”),通过“数组”,您可能想要一个元组或一个列表(它们的行为都类似于其他语言的数组) --

 >>> a = "hello, world"
 >>> list(a)
['h', 'e', 'l', 'l', 'o', ',', ' ', 'w', 'o', 'r', 'l', 'd']
>>> tuple(a)
('h', 'e', 'l', 'l', 'o', ',', ' ', 'w', 'o', 'r', 'l', 'd')

A use of map here would be if you start with a list of strings instead of a single string - map can listify all of them individually: 一个用的map ,如果你开始字符串,而不是一个单一的字符串列表这里是- map可以单独listify所有的人:

>>> a = ["foo", "bar", "baz"]
>>> list(map(list, a))
[['f', 'o', 'o'], ['b', 'a', 'r'], ['b', 'a', 'z']]

Note that map(list, a) is equivalent in Python 2, but in Python 3 you need the list call if you want to do anything other than feed it into a for loop (or a processing function such as sum that only needs an iterable, and not a sequence). 需要注意的是map(list, a)在Python 2相当,但在Python 3你需要的list ,如果你想做的任何事情比饲料它变成一个其他呼叫for环(或处理功能如sum ,仅需要一个迭代,而不是序列)。 But also note again that a list comprehension is usually preferred: 但也请注意,通常首选列表理解:

>>> [list(b) for b in a]
[['f', 'o', 'o'], ['b', 'a', 'r'], ['b', 'a', 'z']]

#3楼

map creates a new list by applying a function to every element of the source: map通过将函数应用于源的每个元素来创建新列表:

xs = [1, 2, 3]

# all of those are equivalent — the output is [2, 4, 6]
# 1. map
ys = map(lambda x: x * 2, xs)
# 2. list comprehension
ys = [x * 2 for x in xs]
# 3. explicit loop
ys = []
for x in xs:
    ys.append(x * 2)

n-ary map is equivalent to zipping input iterables together and then applying the transformation function on every element of that intermediate zipped list. n元map等效于将输入可迭代项压缩在一起,然后将转换函数应用于该中间压缩列表的每个元素。 It's not a Cartesian product: 不是笛卡尔积:

xs = [1, 2, 3]
ys = [2, 4, 6]

def f(x, y):
    return (x * 2, y // 2)

# output: [(2, 1), (4, 2), (6, 3)]
# 1. map
zs = map(f, xs, ys)
# 2. list comp
zs = [f(x, y) for x, y in zip(xs, ys)]
# 3. explicit loop
zs = []
for x, y in zip(xs, ys):
    zs.append(f(x, y))

I've used zip here, but map behaviour actually differs slightly when iterables aren't the same size — as noted in its documentation, it extends iterables to contain None . 我在这里使用zip ,但是当iterables的大小不同时, map行为实际上略有不同-如其文档中所述,它将iterables扩展为包含None


#4楼

map isn't particularly pythonic. map并不是特别的pythonic。 I would recommend using list comprehensions instead: 我建议改用列表推导:

map(f, iterable)

is basically equivalent to: 基本上等同于:

[f(x) for x in iterable]

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. map本身不能做笛卡尔积,因为其输出列表的长度始终与输入列表相同。 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))

#5楼

Simplifying a bit, you can imagine map() doing something like this: 简化一下,您可以想象map()做这样的事情:

def mymap(func, lst):
    result = []
    for e in lst:
        result.append(func(e))
    return result

As you can see, it takes a function and a list, and returns a new list with the result of applying the function to each of the elements in the input list. 如您所见,它接受一个函数和一个列表,并返回一个新列表,并将该函数应用于输入列表中的每个元素。 I said "simplifying a bit" because in reality map() can process more than one iterable: 我说“简化一点”是因为实际上map()可以处理多个迭代:

If additional iterable arguments are passed, function must take that many arguments and is applied to the items from all iterables in parallel. 如果传递了其他可迭代参数,则函数必须采用那么多参数,并且并行地将其应用于所有可迭代对象的项。 If one iterable is shorter than another it is assumed to be extended with None items. 如果一个可迭代项比另一个可迭代项短,则假定它使用None项目扩展。

For the second part in the question: What role does this play in making a Cartesian product? 对于问题的第二部分:这在制造笛卡尔积中起什么作用? well, map() could be used for generating the cartesian product of a list like this: 好吧, map() 用于生成列表的笛卡尔积,如下所示:

lst = [1, 2, 3, 4, 5]

from operator import add
reduce(add, map(lambda i: map(lambda j: (i, j), lst), lst))

... But to tell the truth, using product() is a much simpler and natural way to solve the problem: ...但是说实话,使用product()是解决问题的简单得多且自然的方法:

from itertools import product
list(product(lst, lst))

Either way, the result is the cartesian product of lst as defined above: 无论哪种方式,结果都是如上所述的lst的笛卡尔积:

[(1, 1), (1, 2), (1, 3), (1, 4), (1, 5),
 (2, 1), (2, 2), (2, 3), (2, 4), (2, 5),
 (3, 1), (3, 2), (3, 3), (3, 4), (3, 5),
 (4, 1), (4, 2), (4, 3), (4, 4), (4, 5),
 (5, 1), (5, 2), (5, 3), (5, 4), (5, 5)]

#6楼

The map() function is there to apply the same procedure to every item in an iterable data structure, like lists, generators, strings, and other stuff. 使用map()函数可将相同的过程应用于可迭代数据结构中的每个项目,例如列表,生成器,字符串和其他内容。

Let's look at an example: map() can iterate over every item in a list and apply a function to each item, than it will return (give you back) the new list. 让我们看一个示例: map()可以遍历列表中的每个项目并将一个函数应用于每个项目,这样它将返回(给您返回)新列表。

Imagine you have a function that takes a number, adds 1 to that number and returns it: 假设您有一个接受数字的函数,将数字加1并返回:

def add_one(num):
  new_num = num + 1
  return new_num

You also have a list of numbers: 您还有一个数字列表:

my_list = [1, 3, 6, 7, 8, 10]

if you want to increment every number in the list, you can do the following: 如果要递增列表中的每个数字,可以执行以下操作:

>>> map(add_one, my_list)
[2, 4, 7, 8, 9, 11]

Note: At minimum map() needs two arguments. 注意:至少map()需要两个参数。 First a function name and second something like a list. 首先是函数名称,其次是列表。

Let's see some other cool things map() can do. 让我们看看map()可以做的其他一些很棒的事情。 map() can take multiple iterables (lists, strings, etc.) and pass an element from each iterable to a function as an argument. map()可以采用多个可迭代项(列表,字符串等),并将每个可迭代项中的元素作为参数传递给函数。

We have three lists: 我们有三个列表:

list_one = [1, 2, 3, 4, 5]
list_two = [11, 12, 13, 14, 15]
list_three = [21, 22, 23, 24, 25]

map() can make you a new list that holds the addition of elements at a specific index. map()可以使您成为一个新列表,其中包含特定索引处元素的添加。

Now remember map() , needs a function. 现在记住map() ,需要一个函数。 This time we'll use the builtin sum() function. 这次,我们将使用内置的sum()函数。 Running map() gives the following result: 运行map()得到以下结果:

>>> map(sum, list_one, list_two, list_three)
[33, 36, 39, 42, 45]

REMEMBER: 记得:
In Python 2 map() , will iterate (go through the elements of the lists) according to the longest list, and pass None to the function for the shorter lists, so your function should look for None and handle them, otherwise you will get errors. 在Python 2 map() ,将根据最长的列表进行迭代(遍历列表中的元素),并将None传递给较短列表的函数,因此您的函数应查找None并进行处理,否则您将获得错误。 In Python 3 map() will stop after finishing with the shortest list. 在Python 3中, map()将在完成最短列表后停止。 Also, in Python 3, map() returns an iterator, not a list. 同样,在Python 3中, map()返回一个迭代器,而不是列表。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值