提取列表中的元素之后,放在其他的数据中,对其处理的时候原来的列表数据也会发生改变
问题
提取列表中的元素,放在其他列表中,在新的列表中处理它的时候,原来列表中的元素也会变化,找了比较长时间才发现这个问题。如下列的示例代码所示:
#给定一个原来的列表
>>> list1=[["a","b"],["c","d"],["e","f"]]
#新建一个空列表
>>> list2=[]
#将1列表中的数据提取出来一个放在2列表中
>>> list2.append(list1[0])
>>> list2
[['a', 'b']]
#对2列表中新添加的数据进行修改
>>> list2[0].append("x")
>>> list2
[['a', 'b', 'x']]
#发现列表1和列表2中的数据同时都发生了改变
>>> list1
[['a', 'b', 'x'], ['c', 'd'], ['e', 'f']]
>>>
解决办法
将原来的数据最底层的数据分别取出来新建列表即可
def copy_list(all_list):
new_list=[]
for list_n in all_list:
list_x=[x for x in list_n]
new_list.append(list_x)
return new_list
>>> list2=list1
>>> list2[0].append("z")
>>> list2
[['a', 'b', 'x', 'z'], ['c', 'd'], ['e', 'f']]
>>> list1
[['a', 'b', 'x', 'z'], ['c', 'd'], ['e', 'f']]
>>> list2=copy_list(list1)
>>> list2[0].append("y")
>>> list2
[['a', 'b', 'x', 'z', 'y'], ['c', 'd'], ['e', 'f']]
>>> list1
[['a', 'b', 'x', 'z'], ['c', 'd'], ['e', 'f']]