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

循环中向全局列表listY添加整数避免值被覆盖的问题求助

问题分析与修复方案

问题根源

你在for循环的每一次迭代中都执行了listY = [],这会每次循环都把listY重置为空列表,导致之前追加的元素全部被清空,最终只能保留最后一次循环添加的元素。

修复方案

方案1:调整全局变量初始化位置

把listY = []移到for循环外面,确保列表只被初始化一次:

def findCypherP1():
    global listY
    listY = []  # 移至循环外,仅初始化一次
    a = 0 # 待加密短语长度
    column = 0 # 加密表列索引
    row = 0
    dictator = encryptionTable[0] # 字母表第一行
    for p in range(len(phrase) * len(dictator)):
        if phrase[a] == dictator[column]:
            print("Column containing cypher Y:", str(column+1))
            listY.append(column)
            a += 1
            column = 0
        if a >= len(phrase):
            print(listY)
            break
        else:
            column += 1

方案2:避免使用全局变量(更推荐)

全局变量容易引发意外问题,更规范的做法是让函数直接返回结果列表:

def findCypherP1():
    listY = []  # 使用局部列表存储结果
    a = 0 # 待加密短语索引
    column = 0 # 加密表列索引
    dictator = encryptionTable[0] # 字母表第一行
    for p in range(len(phrase) * len(dictator)):
        if phrase[a] == dictator[column]:
            print("Column containing cypher Y:", str(column+1))
            listY.append(column)
            a += 1
            column = 0
        if a >= len(phrase):
            print(listY)
            break
        column += 1  # 简化逻辑,无需else分支
    return listY

# 调用函数并获取结果
result = findCypherP1()
print(result)

额外优化提示

  • 无需额外创建column2变量,直接listY.append(column)即可完成存储
  • 循环内的else分支可以省略,因为当a >= len(phrase)时会触发break,不会执行后续的column +=1

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 00:42:10