Python:列表 append 问题
这是我的代码 -
cumulative_nodes_found_list = []
cumulative_nodes_found_total_list = []
no_of_runs = 10
count = 0
while count < no_of_runs:
#My program code
print 'cumulative_nodes_found_list - ' + str(cumulative_nodes_found_list)
cumulative_nodes_found_total_list.insert(count,cumulative_nodes_found_list)
print 'cumulative_nodes_found_total_list - ' + str(cumulative_nodes_found_total_list)
count = count + 1
这是输出的一部分 -
#count = 0
cumulative_nodes_found_list - [0.0, 0.4693999, 0.6482, 0.6927999999, 0.7208999999, 0.7561999999, 0.783399999, 0.813999999, 0.8300999999, 0.8498, 0.8621999999]
cumulative_nodes_found_total_list - [[0.0, 0.4693999, 0.6482, 0.6927999999, 0.7208999999, 0.7561999999, 0.783399999, 0.813999999, 0.8300999999, 0.8498, 0.8621999999]]
#count = 1
cumulative_nodes_found_list - [0.0, 0.55979999999999996, 0.66220000000000001, 0.69479999999999997, 0.72040000000000004, 0.75380000000000003, 0.77629999999999999, 0.79679999999999995, 0.82979999999999998, 0.84850000000000003, 0.85760000000000003]
cumulative_nodes_found_total_list -[[0.0, 0.55979999999999996, 0.66220000000000001, 0.69479999999999997, 0.72040000000000004, 0.75380000000000003, 0.77629999999999999, 0.79679999999999995, 0.82979999999999998, 0.84850000000000003, 0.85760000000000003],
[0.0, 0.55979999999999996, 0.66220000000000001, 0.69479999999999997, 0.72040000000000004, 0.75380000000000003, 0.77629999999999999, 0.79679999999999995, 0.82979999999999998, 0.84850000000000003, 0.85760000000000003]]
当我添加新项目时,旧项目会被新项目替换。这种情况一直在发生。有没有人能告诉我为什么会这样?我试着用'append'代替'insert',但输出还是一样。不过,当我使用'extend'时,我得到了正确的输出,但我需要内部项目是列表,而使用'extend'时我得不到这个。
9 个回答
1
我觉得问题出在你程序的其他部分代码上。
在每次循环中,cummulative_nodes_found_list
里的内容都被直接替换了。
我猜你可能是这样做的:
while count < no_of_runs:
cummulative_nodes_found_list.clear()
#fill up the list with values using whatever program logic you have
cummulative_nodes_found_list.append(1.1)
cummulative_nodes_found_list.append(2.1)
print 'cumulative_nodes_found_list - ' + str(cumulative_nodes_found_list)
cumulative_nodes_found_total_list.insert(count,cumulative_nodes_found_list)
print 'cumulative_nodes_found_total_list - ' + str(cumulative_nodes_found_total_list)
count = count + 1
如果你确实是这样做的,那就不要用'clear()'来清空这个列表,而是创建一个新的列表:
也就是说,把 cummulative_nodes_found_list.clear() 替换成
cummulative_nodes_found_list = []
2
这真是个有趣的调试过程,因为你实际上是在问“我的代码哪里出错了,但我不会给你看代码”。
我能做的就是猜。
我猜测你在内存中重复使用了数组对象。
换句话说,你可能做了这样的事情:
list1.insert(0, list2)
list2.clear()
list2.append(10)
list2.append(15)
list1.insert(0, list2)
因为list1
始终指向同一个数组/列表,而你添加的是对这个对象的引用,而不是它的副本,所以后面的修改会让你觉得你的副本也变了。
换句话说,上面代码的结果将会是:
[[10, 15], [10, 15]]
无论你在第一次添加之前列表里有什么。
试着在每次进入循环体时给这个变化的列表分配一个新的空对象,看看这样是否能解决问题。
6
你需要在循环开始的时候重新绑定一下 cumulative_nodes_found_list
,而不是仅仅把它清空。