Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Random double loop in Python

Tags:

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?


1 Answers

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:
    ...
like image 60
chepner Avatar answered Jan 22 '26 17:01

chepner



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!