In [1]: def my_func(x, *args):
...: return (x, ) + args
...:
In [2]: from functools import partial
In [3]: from itertools import starmap
In [4]: import random
In [5]: samples = [range(random.choice(range(10))) for _ in range(100)]
In [6]: %timeit map(lambda x: my_func(3, *x), samples)
10000 loops, best of 3: 39.2 µs per loop
In [7]: %timeit list(starmap(partial(my_func, 3), samples))
10000 loops, best of 3: 33.2 µs per loop
In [8]: %timeit [my_func(3, *s) for s in samples]
10000 loops, best of 3: 32.8 µs per loop
为了比较起见,让我们稍微改变一下函数
In [9]: def my_func(x, args):
...: return (x, ) + tuple(args)
...:
In [10]: %timeit [my_func(3, s) for s in samples]
10000 loops, best of 3: 37.6 µs per loop
In [11]: %timeit map(partial(my_func, 3), samples)
10000 loops, best of 3: 42.1 µs per loop
我不太确定
map
vs list comprehension的性能,因为通常这是您使用的函数的问题。不管怎样,你的选择是:或者
^{pr2}$与
itertools
中的所有函数一样,starmap
返回一个迭代器,因此如果需要列表,则必须将其传递给list
构造函数。这肯定比listcomp慢。在编辑基准:
为了比较起见,让我们稍微改变一下函数
同样,列表理解更快。在
我认为您的代码只需做一些小的更改即可工作:
如果使用列表理解,则可以解压缩参数列表:
但是你不能用
^{pr2}$map
来做这个。如果坚持使用map
,则需要一个helper函数:相关问题 更多 >
编程相关推荐