Python-用另一个列表中的唯一元素替换列表中的重复元素

时间:2018-12-28 03:03:41

标签: python list dictionary matplotlib seaborn

我正在尝试为列表中的每个重复元素分配唯一的颜色值。为此,我有两个不同的列表,一个是包含重复值的列表(例如labels = [1, 5, 6, 7, 8, 12, 13, 17])。

第二个列表(或列表列表)包含色相信息本身: group_pal = seaborn.husl_palette(len(set(labels)), s=.45)。 这里的关键是group_pal的长度始终是labels中唯一元素的数量。

是否有一个python内衬来执行此操作?

输入:

labels = [0, 0, 0, 1, 1, 2, 3]
group_pal = sns.husl_palette(len(set(labels)), s=.45)

所需的输出:

labels = mapingMacro(labels, group_pal)
labels:
[0.8167028311697733, 0.5345122109266688, 0.5750280113923723]
[0.8167028311697733, 0.5345122109266688, 0.5750280113923723]
[0.8167028311697733, 0.5345122109266688, 0.5750280113923723]
[0.7256380093027939, 0.5865684184445076, 0.45124969098702544]
[0.7256380093027939, 0.5865684184445076, 0.45124969098702544]
[0.601243246823196, 0.6281411529879642, 0.44959498566071004]
[0.46712078684915886, 0.6454760674453914, 0.6277122757100324]

1 个答案:

答案 0 :(得分:0)

使用:

group_pal = [i for x,y in zip(sns.husl_palette(len(set(labels)), s=.45),
                              sorted(set(labels),key=labels.index)) 
             for i in np.repeat([x],labels.count(y),axis=0).tolist()]

现在:

print(group_pal)

是:

[[0.8167028311697733, 0.5345122109266688, 0.5750280113923723],
 [0.8167028311697733, 0.5345122109266688, 0.5750280113923723], 
 [0.8167028311697733, 0.5345122109266688, 0.5750280113923723], 
 [0.601243246823196, 0.6281411529879642, 0.44959498566071004], 
 [0.601243246823196, 0.6281411529879642, 0.44959498566071004], 
 [0.46712078684915886, 0.6454760674453914, 0.6277122757100324], 
 [0.6254162090818173, 0.5854245228463807, 0.7893617517727602]]