# Python map() 函数使用详解(How to use Python map() function)-python

## Python map() 函数使用详解(How to use Python map() function)

### 方法一：

``````1 print(sum([i for i in range(1, 101)]))
2 执行结果：
3 5050``````

### 方法二：

``````def nums_add():
global sum_nums
sum_nums = 0
for i in range(1, 101):
sum_nums +=i
return sum_nums

5050``````

### 方法三：

``````result = reduce(lambda x, y: x + y, [i for i in range(1, 101)])
print(result)

5050``````

### 参数

• function — 函数
• iterable — 一个或多个可迭代对象

### 实例

• 给列表[1,2,3,4]中的每一个元素乘以2，后返回一个新列表
``````print(list(map(lambda x: x * 2, [1, 2, 3, 4])))

[2, 4, 6, 8]``````
• 在1~100中间随机生成整数，然后将这个整数加1

import random

def demo(num: int):
return num + 1

result = list(map(demo,[random.randint(1,100)]))
print(result)

``````import random

def demo(num: int):
return num + 1

result = list(map(demo,[random.randint(1,100)]))
print(result) ``````

————————

### background

Before explaining the map function, let’s do a short answer algorithm?
The title is:
Find 1 + 2, + 3 + 4+ What can we do to solve the sum of 100?

### Method 1:

``````1 print(sum([i for i in range(1, 101)]))
2 执行结果：
3 5050``````

### Method 2:

``````def nums_add():
global sum_nums
sum_nums = 0
for i in range(1, 101):
sum_nums +=i
return sum_nums

5050``````

### Method 3:

``````result = reduce(lambda x, y: x + y, [i for i in range(1, 101)])
print(result)

5050``````

### parameter

• function — 函数
• Iterable — one or more iteratable objects

### example

• Multiply each element in the list [1,2,3,4] by 2 and return to a new list
``````print(list(map(lambda x: x * 2, [1, 2, 3, 4])))

[2, 4, 6, 8]``````
• 在1~100中间随机生成整数，然后将这个整数加1

import random

def demo(num: int):
return num + 1

result = list(map(demo,[random.randint(1,100)]))
print(result)

``````import random

def demo(num: int):
return num + 1

result = list(map(demo,[random.randint(1,100)]))
print(result) ``````