# Python Map 函数的使用

map()是一个 Python 内建函数，它允许你不需要使用循环就可以编写简洁的代码。

map()是一个 Python 内建函数，它允许你不需要使用循环就可以编写简洁的代码。

`map(function, iterable, ...)`

• `function` - 针对每一个迭代调用的函数
• `iterable` - 支持迭代的一个或者多个对象。在 Python 中大部分内建对象，例如 lists, dictionaries, 和 tuples 都是可迭代的。

```directions = ["north", "east", "south", "west"]
directions_upper = []

for direction in directions:
d = direction.upper()
directions_upper.append(d)

print(directions_upper)```

['NORTH', 'EAST', 'SOUTH', 'WEST'

```def to_upper_case(s):
return s.upper()

directions = ["north", "east", "south", "west"]

directions_upper = map(to_upper_case, directions)

print(list(directions_upper))```

['NORTH', 'EAST', 'SOUTH', 'WEST']

```directions = ["north", "east", "south", "west"]

directions_upper = map(lambda s: s.upper(), directions)

print(list(directions_upper))```

```squares = map(lambda n: n*n , range(1, 11))
print(list(squares))```

[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

`range()` 函数生成一系列的整数。

```def multiply(x, y):
return x * y

a = [1, 4, 6]
b = [2, 3, 5]

result = map(multiply, a, b)

print(list(result))```

[2, 12, 30]

```a = [1, 4, 6]
b = [2, 3, 5]

result = map(lambda x, y: x*y, a, b)

print(list(result))```

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

result = map(lambda x, y: x*y, a, b)

print(list(result))```

[2, 12, 30]

Python 的` map()`函数作用于一个可迭代对象，使用一个函数，并且将函数应用于这个可迭代对象的每一个元素。