Python函数式编程之map() reduce()

时间:2022-10-13 08:59:49

map

Python函数式编程之map使用(一个seq)

# 使用map
print map( lambda x: x%3, range(6) ) # [0, 1, 2, 0, 1, 2]

#使用列表解析
print [x%3 for x in range(6)] # [0, 1, 2, 0, 1, 2]

Python函数式编程之map使用(多个seq)

print map( lambda x, y: x * y, [1, 2, 3], [4, 5, 6] )  # [4, 10, 18]

Python函数式编程之map使用(多个seq)

print map( lambda x, y: ( x * y, x + y), [1, 2, 3], [4, 5, 6] )  # [(4, 5), (10, 7), (18, 9)]

Python函数式编程之map使用(func为None)

print map( None, [1, 2, 3], [4, 5, 6] )  # [(1, 4), (2, 5), (3, 6)]

print zip( [1, 2, 3], [4, 5, 6] ) # [(1, 4), (2, 5), (3, 6)]

reduce

Python函数式编程之reduce使用

n = 5
print reduce(lambda x, y: x * y, range(1, n + 1)) # 120

m = 2
n = 5
print reduce( lambda x, y: x * y, range( 1, n + 1 ), m ) # 240