我可以在循环中将变化的整数值写入列表而不覆盖以前的值吗?

问题描述 投票:0回答:2

我有一个带有 if 语句的 for 循环,检查“phrase”中的当前字符是否等于“dictator[column]”中的字符,如果是,它将把字符的位置附加到全局列表“listY”中' 但每次它尝试将 'column' 的值附加到 'listY' 时,它都会覆盖之前存在的值。

这是查找列表“加密表”中字符的 X 和 Y 的代码第一部分的当前代码:

def findCypherP1():
    a = 0 # length of phrase to encrypt (cypher phrase)
    column = 0 # length of encryption section (shuffled alphabet)
    row = 0
    dictator = encryptionTable[0] # first row of the alphabet
    for p in range(len(phrase) * len(dictator)):
        global listY
        listY = []
        if phrase[a] == dictator[column]:
            print("Column containing cypher Y:", str(column+1))
            column2 = column
            listY.append(column2)
            a += 1; column = 0
        if a >= len(phrase):
            print(listY)
            break
        else:
            column += 1

当我运行代码时会发生什么,它是否正确返回字符的 X 值

Column containing cypher Y: 1
Column containing cypher Y: 11
Column containing cypher Y: 12
Column containing cypher Y: 19
Column containing cypher Y: 3
[2]

但是当它将“column”附加到“listY”时,它会覆盖以前的值,我尝试制作 int“column”的副本,但它仅适用于列表。如果您能帮助解决这个问题,那就太好了!谢谢!

python python-3.x list append
2个回答
0
投票

您需要将全局变量 listY 的初始化移到循环之外。如果listY在循环内部,则每次循环迭代时都会重新初始化listY

def findCypherP1():
    global listY
    listY = []
    a = 0 # length of phrase to encrypt (cypher phrase)
    column = 0 # length of encryption section (shuffled alphabet)
    row = 0
    dictator = encryptionTable[0] # first row of the alphabet
    for p in range(len(phrase) * len(dictator)):
        if phrase[a] == dictator[column]:
            print("Column containing cypher Y:", str(column+1))
            column2 = column
            listY.append(column2)
            a += 1; column = 0
        if a >= len(phrase):
            print(listY)
            break
        else:
            column += 1

0
投票

以防万一您无法理解问题下面的注释,需要对代码进行更改:

listY = []
def findCypherP1():
    a = 0 # length of phrase to encrypt (cypher phrase)
    column = 0 # length of encryption section (shuffled alphabet)
    row = 0
    dictator = encryptionTable[0] # first row of the alphabet
    for p in range(len(phrase) * len(dictator)):
        if phrase[a] == dictator[column]:
            print("Column containing cypher Y:", str(column+1))
            column2 = column
            listY.append(column2)
            a += 1; column = 0
        if a >= len(phrase):
            print(listY)
            break
        else:
            column += 1
© www.soinside.com 2019 - 2024. All rights reserved.