python 。我有两个列表,长度相同。这个想法是建立配对数据(用于回归分析)。我找出了循环,它看起来像这样。
a=(1,3,5,7) #first list
b=(2,4,6,10) #second list
w=zip(a,b) #paired values from both lists
i=0
j=0
for each in w:
x= w[i]
for that in xrange(i,len(w)-1):
i+=1
print x, w[i]
j+=1
i=j
输出如我所料——第一对与第二对、第三对……依此类推,然后第二对与第三对、第四对……依此类推(跳过第二对与第一对的组合,因为它是有点像第一对和第二对的组合......)
(1, 2) (3, 4)
(1, 2) (5, 6)
(1, 2) (7, 10)
(3, 4) (5, 6)
(3, 4) (7, 10)
(5, 6) (7, 10) [..] and so on as I was expecting.
问题是 - 是否有其他更短、优化的方法来重写这段代码,也许使用 itertools?
最佳答案
您可以使用 itertools.combinations
与 itertools.izip
:
>>> from itertools import izip, combinations
>>> for a, b in combinations(izip(a, b), 2):
print a, b
...
(1, 2) (3, 4)
(1, 2) (5, 6)
(1, 2) (7, 10)
(3, 4) (5, 6)
(3, 4) (7, 10)
(5, 6) (7, 10)
关于Python,组合,排列无重复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27169444/