4

Python. I have two lists, same length. The idea is to build paired data (for regression analysis). I figured out loops and it look 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 is as I was expected - first pair together with second, third.. so on, then second pair with the third, fourth.. and so on (skipping the combination between second pair and first pair, because it is kinda the same as combination of first and second pairs...)

(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 - is there some other, shorter, optimized ways how to rewrite this code, maybe using itertools?

2 Answers 2

3

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)
Sign up to request clarification or add additional context in comments.

1 Comment

Thanx. Your given answer-code perfectly corresponds to the outcome of my code; though more general answer is given by Mr/Ms babbageclunk ;)
2

Yes: itertools.combinations

print list(itertools.combinations(w, 2))

You mention this in your question - I'm not sure why you wouldn't look in the docs before asking on StackOverflow.

1 Comment

:) I have moments like that too.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.