Skip to content Skip to sidebar Skip to footer

How To Define A Tuple Of Randint Without Repeating Code?

I often get to use tuples of randint for color-values and such like (a, b, c) = randint(0, 255), randint(0, 255), randint(0, 255) when I thought there has to be a better way - is

Solution 1:

Using numpy?

1

import numpy as np
tuple(np.random.randint(256, size=3))
# (222, 49, 14)

Multiple

import numpy as np
n=3
[tuple(i) for i in np.random.randint(256, size=(n,3))] # list# (tuple(i) for i in np.random.randint(256, size=(n,3))) # generator# [(4, 70, 3), (10, 231, 41), (141, 198, 105)]

Speed comparison

(randint(0, 255), randint(0, 255), randint(0, 255))

100000 loops, best of 3: 5.31 µs per loop

tuple(random.randint(0, 255) for _ in range(3))

100000 loops, best of 3: 6.96 µs per loop

tuple(np.random.randint(256, size=3))

100000 loops, best of 3: 4.58 µs per loop

Solution 2:

a, b,c=[randint(0,255)for _ inrange(3)]

Post a Comment for "How To Define A Tuple Of Randint Without Repeating Code?"