分类: Python/Ruby
2009-04-15 15:50:18
代码:
import itertools
import functools
import time
def f(x,y): return x + y
RANGE_I = 800
RANGE_F = 1000
r_i = range(RANGE_I)
r_f = range(RANGE_F)
startTime = time.time()
for i in r_i:
def f2(x): return f(x, i)
map(f2, r_f)
endTime = time.time()
print "Finished in %f seconds!" % (endTime - startTime)
def f1(x, l): return map(lambda n: x+n, l)
startTime = time.time()
list(itertools.imap(f1, r_i, itertools.repeat(r_f)))
endTime = time.time()
print "Finished in %f seconds!" % (endTime - startTime)
startTime = time.time()
for i in r_i:
f3 = functools.partial(f, y = i)
map(f3, r_f)
endTime = time.time()
print "Finished in %f seconds!" % (endTime - startTime)
结果:
Finished in 0.375000 seconds!
Finished in 0.266000 seconds!
Finished in 0.593000 seconds!
似乎imap方法由于不用生成临时函数而速度快一些。
Albert Lee 写道:
> On 26/02/2008, jerryji >> And you really should have tried it out yourself -- >> C:\tmp>type test.py >> from itertools import imap, repeat >> from pprint import pprint >> def f(x, l): >> l = list(range(10)) >> pprint(list(imap(f, li, repeat(l)))) >> C:\tmp>python -V >> C:\tmp>python test.py >> [[0, 1, 2, 3, 4, 5, 6, 7, 8, 9], >> Jerry >> On Feb 25, 1:02 pm, Elias Soong >> > jerryji 写道: >> > > use itertools (built-in) module -- >> > > $ ipython >> > > In [1]: from itertools import imap, repeat >> > > In [2]: l = list(range(10)) >> > > In [3]: l >> > > In [4]: li = list(range(3)) >> > > In [5]: li >> > > In [6]: def f(x, l): >> > > In [7]: list(imap(f, li, repeat(l))) >> > > Cheers, >> > > On Feb 25, 11:02 am, Elias Soong >> > >> 那么如果我们定义的函数是多参数的咋办?比如: >> > >> 想到的一个办法是利用原多参数函数定义在调用map函数之前指定部分参数来做一 >> > >> 有没有其他办法使map函数与多参函数配合呢? >> > >> ---------------------------------------- >> > ----------------------------------------
>> As I said, itertools is a python built-in module (since 2.3).
>> return map(lambda n: x+n, l)
>> li = list(range(3))
>> Python 2.5.1
>> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
>> [2, 3, 4, 5, 6, 7, 8, 9, 10, 11]]
>> > 这样看起来似乎是ipython特有的功能呢。如果是CPython的话是否有其他办法呢?
>> > > Out[3]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>> > > Out[5]: [0, 1, 2]
>> > > ....: return map(lambda n: x+n, l)
>> > > ....:
>> > > Out[7]:
>> > > [[0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
>> > > [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
>> > > [2, 3, 4, 5, 6, 7, 8, 9, 10, 11]]
>> > > Jerry
>> > >> 我们知道map函数可以这样用:
>> > >> def f(x): return x+1
>> > >> map(f,range(10))
>> > >> 我们可以得到:[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>> > >> def f(x,y): return x+y
>> > >> 然后希望在map里面调用f的时候可以指定其中一个参数的值。。作用在数组上。。
>> > >> 个临时函数。。比如变成这样:
>> > >> def f(x,y): return x+y
>> > >> for i in range(3):
>> > >> def f2(x): return f(x,i)
>> > >> map(f2,range(10))
>> > >> 于是得到:
>> > >> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>> > >> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>> > >> [2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
>> > >> ----------------------------------------
>> > ----------------------------------------