python Python map,reduce,过滤lambda表达式
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python Python map,reduce,过滤lambda表达式相关的知识,希望对你有一定的参考价值。
#!/usr/bin/env pypy
import sys
# n * n - 1 * ... * 1
def factorial(n):
return reduce(lambda x,y: x*y, range(1, n+1))
def mapTests():
# [0*0, 1*1, 2*2, ..., 9*9]
a = map(lambda x: x*x, range(10))
print a
# [0+1, 1+2, 2+3, ..., 9+10]
a = map(lambda x,y: x+y, range(10), range(1,11))
print a
def reduceTests():
# 1+2+3+ ... +9
a = reduce(lambda x,y: x+y, range(10))
print a
# 3!
print factorial(3)
# 5 is initial, 1+2+5 = 8
a = reduce(lambda x,y: x+y, range(1,3), 5)
print a
# 3 is intial, 1+2+3+4+5+3 = 18
a = reduce(lambda x,y: x+y, range(1,6), 3)
print a
def filterTests():
a = filter(lambda x: x%2, range(5))
print a
a = filter(lambda x: not x%2, range(5))
print a
a = filter(lambda x: x == 'z', 'zzzabc')
print a
a = filter(lambda x: x != 'z', 'zzzabc')
print a
a = filter(lambda x: not x == 'z', 'zzzabc')
print a
def main():
mapTests()
reduceTests()
filterTests()
return 0
if __name__ == '__main__':
sys.exit(main())
#-*- coding:utf-8 -*-
以上是关于python Python map,reduce,过滤lambda表达式的主要内容,如果未能解决你的问题,请参考以下文章
python-map/reduce
Python3的map/reduce
python的map和reduce和Hadoop的MapReduce有啥关系
Python高级教程-Map/Reduce
python学习进度11(map/reduce)
Python高阶函数_map/reduce/filter函数