如何获取Python数组中元素的第二次出现并为其设置指定颜色
实现方法
核心逻辑是用容器记录标签的出现状态,非首次出现的标签直接赋值为[0,0,0]即可,原有配色规则不需要改动。
修改后完整代码
import numpy as np # 可替换为你的测试用例,例如 labels = np.array([1, 4, 1, 2]) labels = np.array([4, 2, 1, 2]) custom_colors = [] check_colors = [] # 集合用来记录已经出现过的标签值 seen_labels = set() for i in range(len(labels)): current_label = labels[i] check_colors.append(current_label) if current_label in seen_labels: # 已出现过的标签直接设为黑色 color = [0,0,0] else: # 首次出现的标签按原有规则配色 if current_label == 1: color = [1,0,0] elif current_label == 2: color = [.5,.5,.5] elif current_label == 3: color = [0,0,1] else: color = [0,1,0] # 将当前标签标记为已出现 seen_labels.add(current_label) custom_colors.append(color) print(check_colors) print(custom_colors)
运行结果示例
测试用例labels = np.array([1, 4, 1, 2])的输出如下,符合需求:
[1, 4, 1, 2] [[1, 0, 0], [0, 1, 0], [0, 0, 0], [0.5, 0.5, 0.5]]
可选适配方案
如果你需要仅第二次出现的位置设为黑色、第三次及之后出现的位置恢复原有配色,可以将集合替换为计数字典,调整判断逻辑即可:
- 用
seen_count = {}替换集合声明 - 遍历中先获取当前标签的出现次数
count = seen_count.get(current_label, 0) - 仅当
count == 1时赋值黑色,其余情况按原有规则配色 - 每次遍历结束更新计数
seen_count[current_label] = count + 1
内容的提问来源于stack exchange,提问作者sinG20
相关产品推荐
相关产品推荐

