您的位置:首页 > 移动开发

python map reduce apply

2012-07-20 20:11 253 查看
吕sir安排事情做了,不过打算先用python做个原型系统

说实话,我没认真用过一次python

传说python的map,reduce这些都是c语言级的优化,而写循环就会慢很多

所以能用map,reduce的时候就用吧,尽量避免写循环

map(fun , list)

将list的每个元素作用于一元函数fun,并且返回所有fun值的列表

reduce(function, sequence[, initial])

将sequence作用于2元函数function,function有两个参数,第一个为之前运算的值

最后返回一个值

For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates
((((1+2)+3)+4)+5).

apply

apply(object[, args[, kwargs]]) -> value

Call a callable object with positional arguments taken from the tuple args,
and keyword arguments taken from the optional dictionary kwargs.
Note that classes are callable, as are instances with a __call__() method.

Deprecated since release 2.3. Instead, use the extended call syntax:
function(*args, **keywords).

有个函数需要把一个图片拆分为大小相同的很多的小图片

按照以前写程序的思想就是写两重循环了,枚举开始左上角的点。

当然不是不可以,但是我们这里的目的是不写循环,所以来用用map,reduce函数

def split_all_image(im ,size_box):
"""
split the image into many subimages
the subimage's size (x,y) is size_box
type size_box = tuple
ex: split_all_image(im , (16,16))
"""
max_x , max_y = im.size
step_x , step_y = size_box
max_x -= step_x
max_y -= step_y
ys = xrange(0 , max_y  , step_y)
tmp = [map(lambda y : (x,y) , [y for y in ys]) for x in xrange(0 , max_x , step_x)]
xy = reduce(lambda x , y : x + y , tmp)
blocks = map(lambda x : get_signle_block(im , (x[0],x[1],x[0]+step_x,x[1]+step_y)) , xy)
return blocks
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: