# map()函数接收两个参数,一个是函数,一个是Iterable,
# map将传入的函数依次作用到序列的每个元素,并把结果作为新的Iterator返回。
def f(x):
return x *
x
r = map(f, [1, 2, 3, 4, 5, 6, 7, 8, 9])
# f作用掉序列的每个元素上,可提高代码可读性
print(r)
# <map object at 0x0000000002222708>
# 结果r是一个Iterator,Iterator是惰性序列
# 通过list()函数让它把整个序列都计算出来并返回一个list
print(list(r))
# [1, 4, 9, 16, 25, 36, 49, 64, 81]
a = 10
print(
"int:", [a])
# int: [10]
b =
str(a)
print(
'str:', [b])
# str: ['10']
# 把list所有数字转为字符串
print(list(map(str, [1, 2, 3, 4, 5, 6, 7, 8, 9
])))
# ['1', '2', '3', '4', '5', '6', '7', '8', '9']
# -------------------------------------------------------
# reduce把一个函数作用在一个序列[x1, x2, x3, ...]上,
# 这个函数必须接收两个参数,reduce把结果继续和序列的下一个元素做累积计算
def add(x, y):
return x +
y
from functools
import reduce
print(reduce(add, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]))
# 55
# add(add(add(1+2)+3)+4).......
转载于:https://www.cnblogs.com/shaozhiqi/p/11543595.html