Python:列表推导与地图 [英] Python: List Comprehensions vs. map
问题描述
参考这个Python List Comprehension Vs.Map 问题,有人能解释为什么当列表推导式不调用函数时列表推导式比 map
给出更好的结果,即使 map
但是在调用函数时给出了最坏的结果?
Referring to this Python List Comprehension Vs. Map question, can someone explain why List Comprehensions gives better results over map
when list comprehension does not call a function, even when there is no lambda function in the map
but gives the worst result when calling a function?
import timeit
print timeit.Timer('''[i**2 for i in xrange(100)]''').timeit(number = 100000)
print timeit.Timer('''map(lambda i: i**2, xrange(100))''').timeit(number = 100000)
print timeit.Timer(setup="""def my_pow(i):
return i**2
""",stmt="""map(my_pow, xrange(100))""").timeit(number = 100000)
print timeit.Timer(setup="""def my_pow(i):
return i**2
""",stmt='''[my_pow(i) for i in xrange(100)]''').timeit(number = 100000)
结果:
1.03697046805 <-- list comprehension without function call
1.96599485313 <-- map with lambda function
1.92951520483 <-- map with function call
2.23419570042 <-- list comprehension with function call
推荐答案
你所有的计时结果都可以用这些事实来解释:
All your timing results can be explained by theses facts:
CPython 的函数调用开销相当高.
CPython has a rather high function call overhead.
map(f, it)
比 [f(x) for x in it]
略快.
您的代码的第一个版本根本没有定义函数,因此没有函数调用开销.第二个版本需要定义一个函数,所以每次迭代都有函数调用开销.第三个版本完全等同于第二个——函数和 lambda 表达式是一回事.根据事实2,最后一个版本甚至更慢.
The first version of your code does not define a function at all, so there is no function call overhead. The second version needs to define a function, ,so there is function call overhead in every iteration. The third version is completely equivalent to the second one – functions and lambda expressions are the same thing. And the last version is even slower according to fact 2.
这篇关于Python:列表推导与地图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!