Usage of map() function in python

map()  will map the specified sequence according to the provided function.

map(function, iterable, ...)
  • function - function
  • iterable - one or more sequences

When there is only one iterable object:

a = [1, 2, 3, 4, 5, 6, 7, 8, 9]

# 对a内部的元素进行平方

new_a = map(lambda i: i * i, a)

for n in new_a:
    print(n)

The results are as follows:

When there are multiple iterable objects:

a = [1, 2, 3, 4, 5, 6, 7, 8, 9]
b = [10, 20, 30, 40]


new_a = map(lambda i, j, k: i * j, a, b, )

for n in new_a:
    print(n)

The results are as follows:

a = [1, 2, 3, 4, 5, 6, 7, 8, 9]
b = [10, 20, 30, 40]
c = [100, 200, 300]

new_a = map(lambda i, j, k: i * j + k, a, b, c)

for n in new_a:
    print(n)

The results are as follows:

a = [1, 2, 3, 4, 5, 6, 7, 8, 9]
b = [10, 20, 30, 40]
c = [100, 200, 300]
d = [1000, 2000, 3000, 4000]
new_a = map(lambda i, j, k, l: i * j + k + l, a, b, c, d)

for n in new_a:
    print(n)

The results are as follows:

It can be seen that when there are multiple iterable objects, the number of elements in the final returned object is determined by the length of the shortest iterable object.

Guess you like

Origin blog.csdn.net/qq_39197555/article/details/112206294