我有这个函数,它接受一个二维数组,并返回一个字符串。该字符串应该有列,其中每列都是二维数组中的列表。由于某种原因,打印中间 3 个列表时出现问题,我不明白为什么。有谁知道出了什么问题吗?
def printFancyNetwork(self) -> None:
temp_network: list = self.network
to_be_printed: str = ""
while True:
total_empty: int = 0
for layer in temp_network:
if len(layer) != 0:
to_be_printed += f"{layer[0]} "
layer.pop(0)
else:
total_empty += 1
to_be_printed += " "
to_be_printed += "\n"
if total_empty == len(temp_network):
return to_be_printed
这里有一些测试输出,其中每个块都是 for 循环中的迭代(初始列表和最终字符串除外)
Inital: [[0.5, 0.5], [0.4, 0.4, 0.4], [0.4, 0.4, 0.4], [0.4, 0.4, 0.4], [0.3, 0.3, 0.3, 0.3]]
[[0.5], [0.4, 0.4, 0.4], [0.4, 0.4, 0.4], [0.4, 0.4, 0.4], [0.3, 0.3, 0.3, 0.3]]
[[0.5], [0.4, 0.4], [0.4, 0.4], [0.4, 0.4], [0.3, 0.3, 0.3, 0.3]]
[[0.5], [0.4], [0.4], [0.4], [0.3, 0.3, 0.3, 0.3]]
[[0.5], [], [], [], [0.3, 0.3, 0.3, 0.3]]
[[0.5], [], [], [], [0.3, 0.3, 0.3]]
[[], [], [], [], [0.3, 0.3, 0.3]]
[[], [], [], [], [0.3, 0.3, 0.3]]
[[], [], [], [], [0.3, 0.3, 0.3]]
[[], [], [], [], [0.3, 0.3, 0.3]]
[[], [], [], [], [0.3, 0.3]]
[[], [], [], [], [0.3, 0.3]]
[[], [], [], [], [0.3, 0.3]]
[[], [], [], [], [0.3, 0.3]]
[[], [], [], [], [0.3, 0.3]]
[[], [], [], [], [0.3]]
[[], [], [], [], [0.3]]
[[], [], [], [], [0.3]]
[[], [], [], [], [0.3]]
[[], [], [], [], [0.3]]
[[], [], [], [], []]
[[], [], [], [], []]
[[], [], [], [], []]
[[], [], [], [], []]
[[], [], [], [], []]
[[], [], [], [], []]
Final:
0.5 0.4 0.4 0.4 0.3
0.5 0.3
0.3
0.3
我尝试使用
self.network.copy()
创建一个副本,但没有似乎有效果
问题在于,在
temp_network
中对列表进行切片时,你实际上也在修改原始列表
self.network
。这是因为
copy()
创建的是一个浅拷贝,它会复制列表引用而不是创建列表本身的副本。
为了解决这个问题,你需要在
printFancyNetwork
函数中创建一个
self.network
的深拷贝。深拷贝会创建一个全新的对象副本,包括其中的所有嵌套对象。你可以使用
copy.deepcopy()
函数来实现这一点。
以下是如何修改你的代码的方法:
import copy
class YourClass: # 将 YourClass 替换为你的实际类名
# ... 你的其他代码 ...
def printFancyNetwork(self) -> None:
temp_network: list = copy.deepcopy(self.network)
to_be_printed: str = ""
while True:
total_empty: int = 0
for layer in temp_network:
if len(layer) != 0:
to_be_printed += f"{layer[0]} "
layer.pop(0)
else:
total_empty += 1
to_be_printed += " "
to_be_printed += "\n"
if total_empty == len(temp_network):
return to_be_printed
通过使用
copy.deepcopy()
,你在
temp_network
中拥有了
self.network
的一个完全独立的副本。这样一来,在
temp_network
上执行的切片操作就不会影响原始的
self.network
。