How to define a tuple of randint without repeating code?

梦想与她 提交于 2021-01-27 12:08:37

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!