没有
总是对的
回答这个问题,有一些关于处理列表时不同方法的速度的帖子,请参见例如。
here
,
here
或
here
.
最快的方法是什么?可能很大程度上取决于你的清单。
也就是说,让我们看看建议的方法有多快。
对于这样的简单比较,您可以使用
timeit
:
1。案例:for循环
for_case = """newList=[]
for x in theList:
if x > n:
newList.append(x)"""
2。案例:列表理解
list_comp = '[x for x in theList if x > n]'
三。案例:过滤器(不知何故未标记)
filtering = 'list(filter(lambda x: x > n, theList))'
一些准备工作:
import timeit
si = 'theList=range(2000);n=1000;' # using list(range(2000)) has no effect on the ranking
让我们看看:
timeit.timeit(si+list_comp, number=10000)
Out[21]: 1.3985847820003983
timeit.timeit(si+filtering, number=10000)
Out[22]: 3.315784254024038
timeit.timeit(si+for_case, number=10000)
Out[23]: 2.0093530920275953
所以,至少在我的机器上,列表理解会把它带走,然后是
for
-循环,至少在这种情况下
filter
确实是最慢的。