简体   繁体   中英

How can I generate n random numbers without a for loop

I am trying to generate 4 random integers between 0-9. I can easily achieve this using a for-loop:

digits = [random.randrange(10) for i in range(4)]

Assuming it is possible, I was wondering about other ways to yield the same result, perhaps without directly using a for-loop. I was experimenting with itertools and this didn't work:

digits = itertools.repeat(random.randrange(10), 4)

The main purpose of my question is to expose myself to additional methods. Thanks.

numpy.random.randint(0, 10, size=4)

or to use itertools

list(map(random.randrange, itertools.repeat(10, 4)))

or even

list(map(random.randrange, [10]*4))

What about using a generator and a while loop ?

from random import randrange

def rand(val, repeat=4):
    j = 1
    while j <= repeat:
        yield randrange(val)
        j += 1

final = list(rand(10))

Output:

[2, 6, 8, 8]

Also, using a recursion :

from random import randrange

def rand(val, repeat=4, b=1, temp=[]):
    if b < repeat:
        temp.append(randrange(val))
        return rand(val, b= b+1, temp=temp)
    else:
        return temp + [randrange(val)]

final = rand(10)
print(final)

Output:

[1, 9, 3, 1]

This is not really something that I would do, but since you would like to expose yourself to additional methods, then taking advantage of the 0-9 range you can also obtain 4 such integers as follows:

map(int, "%04d"%random.randrange(10**4))

It actually generates a four digit string, and extracts the digits from it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM