python - 向我的矩阵添加值,但结果显示错误
问题描述
我正在尝试在我的号码中附加一个包含 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]]
解决方案
正如@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 的答案,这应该更有意义。只需在此处留下答案以比较您的起源逻辑。
推荐阅读
- android - Android 10 刷卡杀死前台服务
- php - fopen() 使用 Vfs 失败,'无法打开流:“org\bovigo\vfs\vfsStreamWrapper::stream_open”'
- html - 如何在 vue.js 中悬停特定悬停卡时显示内容?
- kendo-grid - Kendo UI JQuery - 网格一键触发多个“读取”、“创建”、“更新”和“销毁”操作
- javascript - 仅在 Web 服务器上运行而不在本地运行的脚本
- javascript - 标题文本没有在reactJs中点击按钮?
- spring-boot - 如何从 Spring WebApplicationContext 中获取 DispatcherServlet?
- android - 当起始滑动点位于可点击视图上时,如何允许滑动视图?
- javascript - 在博客的未来帖子中的主页中显示模糊的图像
- fabricjs - 如何使在fabric js中对多个对象应用过滤器不那么滞后?