Itertools与嵌套循环性能 [英] Itertools vs Nested Loops Performance
本文介绍了Itertools与嵌套循环性能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我必须生成列表中项目的所有2对组合.现在,我知道完成此操作的两种方法:嵌套的for循环和python内置的 itertools
I have to generate all the 2-pair combinations of items in a list. Now, I know of two ways to accomplish this: nested for-loops, and python's built-in itertools:
from itertools import combinations
foo = [1, 2, 3, 4]
for i in xrange(len(foo)):
for j in xrange(i + 1, len(foo)):
print foo[i], foo[j]
for c in combinations(foo, 2):
print c
我的问题是:使用一个相对于另一个有什么显着的优势吗?
My question is: are there any significant advantages to using one over the other?
推荐答案
所以我继续使用Python的 timeit 来测量运行时间,并按照@ user2357112建议修改了第一个循环:
So I went ahead and used Python's timeit to measure the runtimes, modifying the first loop as @user2357112 suggested:
import timeit
from itertools import combinations
foo = [i for i in xrange(0, 1000)]
def loop_test():
combos = []
for i in xrange(len(foo)):
for j in xrange(i + 1, len(foo)):
combos.append((foo[i], foo[j]))
def iter_test():
combos = []
for c in combinations(foo, 2):
combos.append(c)
if __name__ == '__main__':
print timeit.timeit('loop_test()', setup='from __main__ import loop_test', number=1000)
print timeit.timeit('iter_test()', setup='from __main__ import iter_test', number=1000)
输出:
59.1836869717
45.6625859737
有趣的是,似乎 itertools 实际上比嵌套循环快.
Interestingly, it appears as though itertools is in fact faster than the nested loops.
这篇关于Itertools与嵌套循环性能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文