You need to enable JavaScript to run this app. 如何修改代码让Seaborn生成的RGB值列表每个值连续出现两次
优惠活动
大模型
产品
解决方案
定价
更多

如何修改代码让Seaborn生成的RGB值列表每个值连续出现两次

实现方案

你只需要对生成的RGB列表做重复处理即可,以下是两种改动极小的实现方式:

方法1:列表推导式直接修改

几乎不改动原有逻辑,直接在生成RGB值时重复两次再扁平化输出:

import seaborn as sns

def get_colorpalette(colorpalette, file_number):
    palette = sns.color_palette(colorpalette, file_number)
    # 每个RGB值连续添加两次
    rgb = [item for rgb_item in palette 
           for item in ['rgb({},{},{})'.format(*[x*256 for x in rgb_item])] * 2]
    return rgb

方法2:itertools实现(易扩展重复次数)

如果后续可能调整重复次数,用标准库的itertools处理可读性更高:

import seaborn as sns
from itertools import repeat, chain

def get_colorpalette(colorpalette, file_number):
    palette = sns.color_palette(colorpalette, file_number)
    rgb = ['rgb({},{},{})'.format(*[x*256 for x in rgb_item]) for rgb_item in palette]
    # 每个元素重复2次后合并为一维列表,要改重复次数仅需修改第二个参数即可
    rgb = list(chain.from_iterable(repeat(item, 2) for item in rgb))
    return rgb

两种方法的输出效果完全一致,返回的列表中每个RGB值都会连续出现两次。

内容的提问来源于stack exchange,提问作者18aaa

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.19 09:06:00