虽然看起来很糟糕,但我并没有找到一种更好/更有效的方法来做这件事:

ae    = np.arange(0.0,1,0.05)
aee   = np.arange(0.3,1.01,0.345)
aef   = np.arange(0.3,1.01,0.345)
random.shuffle(ae)
random.shuffle(aee)
random.shuffle(aef)
for item_a in aee:
    for item_b in ae:
        for item_c in aef:
            rlist.append(colorsys.hsv_to_rgb(item_b,item_a,item_c))

思想?

最佳答案

import numpy as np
import random
import itertools
import colorsys
hue, saturation, value = np.arange(0.0,1,0.05), np.arange(0.3,1.01,0.345), np.arange(0.3,1.01,0.345)
rlist= [colorsys.hsv_to_rgb(hue, saturation, value) for hue, saturation, value in
        itertools.product(random.sample(hue,len(hue)), random.sample(saturation, len(saturation)), random.sample(value, len(value)))]
print rlist

编辑:random.sample从完全填充避免就地单独洗牌
不带itertools的版本:
# without itertools
import numpy as np
import random
from pprint import pprint
import colorsys
hues, saturations, values = np.arange(0.0,1,0.05), np.arange(0.3,1.01,0.345), np.arange(0.3,1.01,0.345)
rlist= [colorsys.hsv_to_rgb(hue, saturation, value)
        for hue in random.sample(hues,len(hues))
        for saturation in random.sample(saturations, len(saturations))
        for value in random.sample(values, len(values))]
pprint(rlist)

您还可以从文档中包含itertools.product的定义(我在服务器中名为it.py的模块中这样做,并使用它代替itertools):
product = None
from itertools import *
if not product:
    def product(*args, **kwds):
        # product('ABCD', 'xy') --> Ax Ay Bx By Cx Cy Dx Dy
        # product(range(2), repeat=3) --> 000 001 010 011 100 101 110 111
        pools = map(tuple, args) * kwds.get('repeat', 1)
        result = [[]]
        for pool in pools:
            result = [x+[y] for x in result for y in pool]
        for prod in result:
            yield tuple(prod)

我通常将itertools用作:
import itertools as it

But in the server it is replaced by
import it

关于python - 建议更优雅地编写此小段代码,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/3971916/

10-11 01:56
查看更多