如何在不重复代码的情况下定义randint元组?

时间:2017-08-04 20:47:37

标签: python python-3.x iterable-unpacking

我经常使用randint元组来表示颜色值,例如

(a, b, c) = randint(0, 255), randint(0, 255), randint(0, 255)

当我认为必须有更好的方法 - 是吗?

2 个答案:

答案 0 :(得分:2)

使用numpy?

1

null

多个

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

速度比较

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)]
  

100000个循环,最佳3:每循环5.31μs

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

100000个循环,最佳3:每循环6.96μs

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

100000次循环,最佳3次:每次循环4.58μs

答案 1 :(得分:1)

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