问题
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 there?
回答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
回答2:
a, b, c = [randint(0, 255) for _ in range(3)]
来源:https://stackoverflow.com/questions/45515276/how-to-define-a-tuple-of-randint-without-repeating-code