当 Reduce 遇上 lambda

# 连续计算,连续调用lambda
list_x = range(1, 10, 1)
rest_reduce_1 = reduce(lambda x, y: x * y, list_x)
print(rest_reduce_1)

# 设定初始值
rest_reduce_2 = reduce(lambda x, y: x * y, list_x, 2)
print(rest_reduce_2)

为了更清晰的看到内部机制,用字符模拟一下这个过程:

list_str = ['1', '2', '3', '4', '5']
rest_reduce_3 = reduce(lambda x, y: x+y, list_str)
print(rest_reduce_3)
12345

# 设定初始值
rest_reduce_4 = reduce(lambda x, y: x+y, list_str, 'a')
print(rest_reduce_4)
a12345

 

posted @ 2018-07-27 14:13  因为专注。所以专业  阅读(374)  评论(0)    收藏  举报