Skip to content Skip to sidebar Skip to footer

How To Do C++ Style(indexed) Nested Loops In Python?

What is the equivalent of the following in python? for (i=0; i

Solution 1:

I intepret what you're asking as

How can I iterate over all pairs of distinct elements of a container?

Answer:

>>>x = {1,2,3}>>>import itertools>>>for a, b in itertools.permutations(x, 2):...print a, b... 
1 2
1 3
2 1
2 3
3 1
3 2

EDIT: If you don't want both (a,b) and (b,a), just use itertools.combinations instead.

Solution 2:

Since your two questions are different, here is solution for your second problem:

for i in xrange(len(A)):
    for j in xrange(len(A)):
        if i != j:
            do_stuff(A[i], A[j])

or usingitertools (I think using the included batteries is very pythonic!):

import itertools

for a, b in itertools.permutations(A, 2):
    do_stuff(a, b)

This applies do_stuff to all combinations of 2 different elements from A. I you want to store the result just use:

[do_stuff(a, b) for a, b in itertools.permutations(A, 2)]

Solution 3:

How about:

for i inrange(0,n):
    for j inrange (i+1,n):
    # do stuff

Solution 4:

for i inrange(0,n):
   for j inrange(i+1,n):
   # do stuff

Solution 5:

Still can't leave comments.. but basically what the other two posts said - but get in the habit of using xrange instead of range.

foriinxrange(0,n):
   forjinxrange(i+1,n):
   # do stuff

Post a Comment for "How To Do C++ Style(indexed) Nested Loops In Python?"