系列和并行映射

map() 是一个内置函数,这意味着它可以在任何地方使用,而无需使用’import’语句。它就像 print() 一样随处可见如果你看一下例 5,你会看到我必须使用 import 语句才能使用漂亮的 print(import pprint)。因此 pprint 不是内置函数

系列映射

在这种情况下,iterable 的每个参数作为参数以递增的顺序提供给映射函数。当我们只有一个可迭代映射并且映射函数需要单个参数时,就会出现这种情况。

例 1

insects = ['fly', 'ant', 'beetle', 'cankerworm']
f = lambda x: x + ' is an insect'
print(list(map(f, insects))) # the function defined by f is executed on each item of the iterable insects

结果是

['fly is an insect', 'ant is an insect', 'beetle is an insect', 'cankerworm is an insect']

例 2

print(list(map(len, insects))) # the len function is executed each item in the insect list

结果是

[3, 3, 6, 10]

并行映射

在这种情况下,映射函数的每个参数都是并行地从所有迭代(每个迭代中的一个)中拉出。因此,提供的可迭代次数必须与函数所需的参数数量相匹配。

carnivores = ['lion', 'tiger', 'leopard', 'arctic fox']
herbivores = ['african buffalo', 'moose', 'okapi', 'parakeet']
omnivores = ['chicken', 'dove', 'mouse', 'pig']

def animals(w, x, y, z):
    return '{0}, {1}, {2}, and {3} ARE ALL ANIMALS'.format(w.title(), x, y, z)

例 3

# Too many arguments
# observe here that map is trying to pass one item each from each of the four iterables to len. This leads len to complain that
# it is being fed too many arguments
print(list(map(len, insects, carnivores, herbivores, omnivores)))

结果是

TypeError: len() takes exactly one argument (4 given)

例 4

# Too few arguments
# observe here that map is suppose to execute animal on individual elements of insects one-by-one. But animals complain when
# it only gets one argument, whereas it was expecting four.
print(list(map(animals, insects)))

结果是

TypeError: animals() missing 3 required positional arguments: 'x', 'y', and 'z'

例 5

# here map supplies w, x, y, z with one value from across the list
import pprint
pprint.pprint(list(map(animals, insects, carnivores, herbivores, omnivores)))

结果是

 ['Fly, lion, african buffalo, and chicken ARE ALL ANIMALS',
 'Ant, tiger, moose, and dove ARE ALL ANIMALS',
 'Beetle, leopard, okapi, and mouse ARE ALL ANIMALS',
 'Cankerworm, arctic fox, parakeet, and pig ARE ALL ANIMALS']