建议更优雅地编写这一小段代码

时间:2010-10-19 19:23:16

标签: python

虽然看起来很糟糕,但我找不到更好/更有效的方法:

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

想法?

4 个答案:

答案 0 :(得分:4)

如果您不想随机播放rlist,而是初始列表,那么您可以尝试将最后四行放入列表理解中:

rlist = [ colorsys.hsv_to_rgb(b, a, c) for c in aef for b in ae for a in aee ] 

答案 1 :(得分:4)

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

但在服务器中它被

取代
import it

答案 2 :(得分:1)

你首先不需要洗牌,因为你会做笛卡尔积... ...

import itertools
import colorsys


hsv_iter = itertools.product(np.arange((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, lightness, saturation)
         for hue, lightness, saturation in hsv_ite]

# you can shuffle now the list if you want
random.shuffle(rlist)

答案 3 :(得分:1)

愚蠢的oneliner:

rlist = [colorsys.hsv_to_rgb(b, a, c) for c in random.sample(aef,len(aef))
                                      for b in random.sample(ae,len(ae)) 
                                      for a in random.sample(aee,len(aee))] 

random.sample(x,len(x))(2.3中的新内容)几乎等同于random.shuffle(x),但它返回列表的随机副本而不是None

这可能比洗牌或其他任何东西慢得多,而且你没有保留随机列表的副本(如果你愿意的话)。