You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python自动绘画程序列表循环故障:非匹配项仅迭代单个元素

自动绘画程序循环逻辑修复

问题背景

我正在开发一款自动绘画程序,其中paint_at()函数用于在x、y坐标(范围0至31)处绘制选中的颜色,select_color()函数用于选择十六进制格式的颜色。当前问题出在for code in hex_codes:循环中:当颜色不匹配时,循环仅迭代一个像素而非全部;只有#000000能遍历所有代码。我需要实现遍历所有绘画代码,仅绘制匹配项的功能。

循环迭代输出日志

Color: #000000, Code: #75403a
Color: #000000, Code: #b57051
Color: #000000, Code: #753e39
Color: #000000, Code: #b86f4f
Color: #000000, Code: #754038
Color: #000000, Code: #e3a870
Color: #000000, Code: #6a4437
Color: #000000, Code: #347243
Color: #000000, Code: #7a9a5b
Color: #000000, Code: #347241
Color: #000000, Code: #67c451
Color: #000000, Code: #7c9c5b
Color: #000100, Code: #000000
Color: #020200, Code: #000000
Color: #010300, Code: #000000
Color: #020401, Code: #000000
Color: #000501, Code: #000000
Color: #040402, Code: #000000

原代码

x_count = 0
y_count = 0
num = 1
painted = []
while num < len(hex_codes):
    color = hex_codes[num-1]
    if color not in painted:
        if color == "#ffffff":
            color = hex_codes[num]
        select_color(color)
        time.sleep(0.02)
        for code in hex_codes:
            print("Color: " + color + ", Code: " + code)
            if code == color:
                paint_at(x_count, y_count)
            x_count += 1
            if x_count == 32:
                x_count = 0
                y_count += 1
            if y_count == 32:
                break
        painted.append(color)
    num +=1

问题分析

  1. 坐标未重置:每次处理新颜色时,全局的x_count和y_count没有重置为(0,0),导致后续颜色的遍历从上次结束的位置开始,很快触发y_count == 32的终止条件,提前退出循环。
  2. 遍历逻辑冗余:用while循环通过索引遍历颜色列表,不仅代码繁琐,还容易出现索引操作错误。
  3. 白色处理逻辑有隐患:直接将#ffffff替换为hex_codes[num]可能触发索引越界,且逻辑不符合遍历所有匹配项的需求。

修复后的代码

x_count = 0
y_count = 0
painted = []

# 遍历所有颜色,跳过已处理的颜色
for color in hex_codes:
    if color in painted:
        continue
    
    # 白色特殊逻辑(可根据需求调整,比如跳过或替换)
    if color == "#ffffff":
        continue
    
    select_color(color)
    time.sleep(0.02)
    
    # 每次处理新颜色时,重置坐标到画布起点
    current_x = 0
    current_y = 0
    
    # 完整遍历所有像素代码
    for code in hex_codes:
        if code == color:
            paint_at(current_x, current_y)
        
        # 更新坐标
        current_x += 1
        if current_x == 32:
            current_x = 0
            current_y += 1
        
        # 超出画布范围则停止遍历
        if current_y == 32:
            break
    
    painted.append(color)

修复要点

  • 为每个颜色单独维护遍历坐标current_x和current_y,确保每次处理新颜色都从(0,0)开始完整遍历所有像素。
  • 用for color in hex_codes替代while循环,简化遍历逻辑,避免索引错误。
  • 优化白色的处理逻辑(可根据实际需求调整,比如跳过白色或替换为目标颜色)。
  • 保证每个颜色都能完整遍历所有hex_codes代码,仅在代码匹配时执行绘制操作。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 07:13:22