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

2024-04-19 05:44:56 发布

您现在位置: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))

有什么想法?在


Tags: 方法infornprandomitemhsvshuffle
3条回答
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

编辑:随机抽样从完全人口中避免在适当的单独洗牌

不带itertools的版本:

^{pr2}$

您还可以包括itertools.product从文档(我在名为它。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

你不需要在一开始就把每个列表打乱,因为你要做一个笛卡尔积。。。

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)

如果您不想对rlist进行无序排列,而是对初始列表进行无序排列,则可以尝试将最后四行放入列表理解中:

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

相关问题 更多 >