user12417848
user12417848

Reputation:

Random double loop in Python

I would like to create a random double loop in Python.

For example, for (N,N)=(2,2) the program should give:

0 1
0 0
1 1
1 0

Or another example

0 0
1 1
1 0
0 1

So far, I have done this:

r1 = list(range(2))
r2 = list(range(2))
random.shuffle(r1)
random.shuffle(r2)
for i in r1:
    for j in r2:
        # Do something with i

This, however, does not give the desired result, because I want i's to be shuffled too and not give for example all (1,x) sequentially. Any ideas?

Upvotes: 3

Views: 87

Answers (1)

chepner
chepner

Reputation: 531165

Shuffle the product of the ranges, not each individual range.

import itertools


pairs = list(itertools.product(r1, r2))  # [(i,j) for i in r1 for j in r2]
random.shuffle(pairs)

for i, j in pairs:
    ...

Upvotes: 5

Related Questions