0

is there a way to make two ranges in for loop. I have to check lets say 10 arrays between each other, but if array1 is picked it shouldn't check with itself. If array1 is picked then array1 should be checked with arrays2-10. if 2nd is picked it should be checked with array1 and array3-10.

I found a chain function but it doesn't seem to work properly in my case or I do something wrong.

for i in range (1,11): 
    test_array is picked 
    for j in chain(range(1,i),range(i+1,11)):
        does the check between test_array and all the other arrays Excluding the one picked as test_array

for i in range(1,11):
   pick test_array
       for j in range (1,11):
           if (j==i):
                 continue
             .... 

this peace according to the tests compares array1 with itself the above code works for 2 for loops but I have nested more than 3 and with continue it goes all the way down, which is not I want Thanks

Found the answer I was looking for :

for i in range(1,11):
    do something.
    for j in range(1,i) + range((i+1),11): 
        do something
3
  • It is not clear what exactly you are looking for, please provide some examples. Mar 27, 2014 at 9:28
  • I want to make for loop that excludes certain number from the loop. for example if 2 is picked it should go like this (1,3,4,5,6,7,8,9,10) and so on, hope that makes it clearer Mar 27, 2014 at 9:31
  • why not add if j == i: continue instead?
    – m.wasowski
    Mar 27, 2014 at 9:31

2 Answers 2

0

use itertools.combinations():

import itertools
arrays = [[x] for x in 'abcd']
# [['a'], ['b'], ['c'], ['d']]

for pair in itertools.combinations(arrays, 2):
    print pair # or compare, or whatever you want to do with this pair
0

You can use itertools.permutations here:

import itertools as IT
from math import factorial

lists = [[1, 2], [3,4], [4,5], [5,6]]
n = len(lists)
for c in IT.islice(IT.permutations(lists, n), 0, None, factorial(n-1)):
    current = c[0]
    rest = c[1:]
    print current, rest

Output:

[1, 2] ([3, 4], [4, 5], [5, 6])
[3, 4] ([1, 2], [4, 5], [5, 6])
[4, 5] ([1, 2], [3, 4], [5, 6])
[5, 6] ([1, 2], [3, 4], [4, 5])

And another way using slicing:

lists = [[1, 2], [3,4], [4,5], [5,6]]
n = len(lists)
for i, item in enumerate(lists):
    rest = lists[:i] + lists[i+1:]
    print item, rest

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.