Python, combinations, permutations without repeating
Python. I have two lists, the same length. The idea is to create paired data (for regression analysis). I figured out the loops and it looks like this.
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
The output will be as I expected - first a pair together with the second, the third ... so on, then the second pair with the third, the fourth ... and so on (skipping the combination between the second pair and the first pair, because it's kind of like a combination of the first and second pair ...)
(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.
The question is: are there any other, shorter, more streamlined ways to rewrite this code, perhaps using itertools?
+3
source to share
2 answers
You can use itertools.combinations
with 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)
+3
source to share