Map

python3.6

map(func, *iterables) --> map object

Make an iterator that computes the function using arguments from
each of the iterables. Stops when the shortest iterable is exhausted.


map(func, *iterables) --> map object
  • func 逻辑简单lambda匿名函数,逻辑复杂需自拟;
  • *iterables 可迭代对象
  • map函数所得的结果也是一个可迭代对象,但是只能遍例一次.

例: 自定义函数模拟内置函数map,列表自增减1及平方


内置函数map实现列表自增减1及平方

li = [1, 2, 3, 4, 5, 6, 7, 8, 9]
# 自增1
print(list(map(lambda x: x + 1, li)))
# 自减1
print(list(map(lambda x: x - 1, li)))
# 平方
print(
    list(
        map(lambda x: x ** 2, li)
    )
)

自定义函数实现

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


# 自增1
def add1(x):
    return x + 1


# 自减1
def red1(x):
    return x - 1


# 平方
def square(x):
    return x ** 2


def map_test(func, l):
    tl = []
    for i in l:
        tl.append(func(i))
    return tl

# 调用上面定义的函数
print(map_test(add1, li))
print(map_test(red1, li))
print(map_test(square, li))

自定义函数+匿名函数实现

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

def map_test(func, l):
    tl = []
    for i in l:
        tl.append(func(i))
    return tl

print(map_test(lambda x: x + 1, li))
print(map_test(lambda x: x - 1, li))
print(map_test(lambda x: x ** 2, li))

原文地址:https://www.cnblogs.com/IMxY/p/6957911.html