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

背景

在讲解map函数之前,我们先做个简答的算法?
题目是这样:
求出1+2,+3+4…+100的和,大家想想用什么办法可以解决?
我想到了三种方法,大家还有其他更好方法吗?请留言一起学习、沟通

方法一:

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
print(nums_add())
执行结果:
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) 

 转载至:https://mp.weixin.qq.com/s/G0RWcFtm5QPSUK44rGgE3A

————————

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?
I think of three methods. Do you have any other better methods? Please leave a message to learn and communicate together

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
print(nums_add())
执行结果:
5050

Method 3:

result = reduce(lambda x, y: x + y, [i for i in range(1, 101)])
print(result)
执行结果:
5050

describe

grammar

parameter

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

Return value

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) 

 转载至:https://mp.weixin.qq.com/s/G0RWcFtm5QPSUK44rGgE3A