python中有趣的函数

王朝学院·作者佚名  2016-08-27
窄屏简体版  字體: 小  |  中  |  大  |  超大  

filter(function, sequence):对sequence中的item依次执行function(item),将执行结果为True的item组成一个List/String/Tuple(取决于sequence的类型)返回:

>>> def f(x): return x % 2 != 0 and x % 3 != 0

>>> filter(f, range(2, 25))

[5, 7, 11, 13, 17, 19, 23]

>>> def f(x): return x != 'a'

>>> filter(f, "abcdef")

'bcdef'

map(function, sequence) :对sequence中的item依次执行function(item),见执行结果组成一个List返回:

>>> def cube(x): return x*x*x

>>> map(cube, range(1, 11))

[1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]

>>> def cube(x) : return x + x

...

>>> map(cube , "abcde")

['aa', 'bb', 'cc', 'dd', 'ee']

另外map也支持多个sequence,这就要求function也支持相应数量的参数输入:

>>> def add(x, y): return x+y

>>> map(add, range(8), range(8))

[0, 2, 4, 6, 8, 10, 12, 14]

reduce(function, sequence, starting_value):对sequence中的item顺序迭代调用function,如果有starting_value,还可以作为初始值调用,例如可以用来对List求和:

>>> def add(x,y): return x + y

>>> reduce(add, range(1, 11))

55 (注:1+2+3+4+5+6+7+8+9+10)

>>> reduce(add, range(1, 11), 20)

75 (注:1+2+3+4+5+6+7+8+9+10+20)

 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
© 2005- 王朝網路 版權所有 導航