首页 > 解决方案 > 向我的矩阵添加值,但结果显示错误

问题描述

我正在尝试在我的号码中附加一个包含 4 个字母的列表作为[[a, b, c, d]]列表类型。
我正在遍历一个列表并将该字母附加到一个临时列表中,然后将其附加到我的主列表中以使其成为一个矩阵。(8, 26)但是,由于某种原因,主列表仅存储数字

ciphertext = "asfgasgsaga"
counter = 0
templist = []
xyz = []

for abc in ciphertext:
    if(counter == 5):
        print(templist)
        xyz.append(templist)
        templist.clear()
        counter = 0
    else:
        templist.append(abc);
    counter += 1

print(xyz)

结果是由于某种原因给[[8, 26]]

标签: python

解决方案


正如@zvone 所说,不要使用相同的数组并清除它,因为它们引用相同的内存;

ciphertext = "asfgasgsaga"
counter = 0
templist = []
xyz = []

for abc in ciphertext:
    if(counter == 4):
        print(templist)
        xyz.append(templist)
        templist = []     # <--- use a new empty array
        counter = 0
    else:
        templist.append(abc);
        counter += 1

print(xyz)

此外,正确的逻辑(处理小于 4 的字母)应该是:

ciphertext = "asfgasgsaga"
counter = 0
templist = []
xyz = []

for abc in ciphertext:
    templist.append(abc);
    counter += 1
    if(counter == 4):
        print(templist)
        xyz.append(templist)
        templist = []
        counter = 0

if templist:
    xyz.append(templist)

print(xyz)

只需查看@Toan Quoc Ho 的答案,这应该更有意义。只需在此处留下答案以比较您的起源逻辑。


推荐阅读