0

I'm iterating over a list (numpy array with one dimension to be exact) and I need to pick an index form this list that is random and different than current iterator.

The most important thing is constant and equal probability over the range.

list = ['a','b','c','d']
for idx , e in enumerate(list):
  return random.randrange(len(list)-1) # but without possibility of geting idx

-- EDIT -- Wouldnt that work:

    x = np.array([1,2,3,4])
    for idx, e in enumerate(x):
        l = list(range(0, len(x)))
        l.pop(idx)
        res = random.choice(l)
        print(idx, res)
2
  • Does this answer your question? Generate random number in range excluding some numbers Commented Apr 5, 2020 at 10:56
  • Honestly your answer below looks better. But it still destroys probability distribution. I think. Maybe to rephrase it would be better to select a value from a list of all indexes without the one. using random.choice() Commented Apr 5, 2020 at 11:03

3 Answers 3

1

Depending on how large the list is, the chance of accidentally hitting idx might be small enough. So I usually do something like this:

def randrange(n, without=None):
    while True:
        s = random.randrange(n)
        if s != without:
            return s

To use it, just replace your return statement with return randrange(len(list)-1, idx)

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, I will do that if there is no better solution. :D
0

You could try using

list = ['a', 'b', 'c', 'd']
for idx, e in enumerate(list):
    temp = math.randrange(0, len(list)) # You would use -1, if it was randint()
    while temp == idx:
        temp = math.randrange(0, len(list))
    return temp

Comments

0

What if you add an if statement to check whether the random number you get is different from the iterator?

import random

list1 = ['a','b','c','d']
for idx, e in enumerate(list1):
   randnum = random.randrange(len(list1)-1)
if randnum != idx:
    return randnum

One more advice: since the list library is reserved by python. better not use it as a variable name.

Comments

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.