我需要生成一个列表中所有可能的2个元素组合。现在,我知道两种方法可以实现这个目标:使用嵌套的for循环或者使用Python内置的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
我的问题是:使用其中之一是否有明显的优势?
foo = range(1000)
设置为一个良好的测试即可。 - Alex Hall