系列和並行對映

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']