【发布时间】:2015-02-11 15:40:41
【问题描述】:
我正在尝试从循环中打印列表列表,但输出错误! 附加到较大列表的最后一个列表正在重复。
我期待的输出:
FINAL LIST:
[[(1, 2), (2, 3)],
[(2, 3), (3, 4)]]
我得到的输出:
FINAL LIST:
[[(2, 3), (3, 4)],
[(2, 3), (3, 4)]]
我在这里做错了什么?这是我的代码:
a = []
count = 1
#Function that generates some nos. for the list
def func():
del a[:]
for i in range(count,count+2):
x = i
y = i+1
a.append((x,y))
print '\nIn Function:',a #List seems to be correct here
return a
#List of lists
List = []
for i in range(1,3):
b = func() #Calling Function
print 'In Loop:',b #Checking the value, list seems to be correct here also
List.append(b)
count = count+1
print '\nList of Lists:'
print List
【问题讨论】:
-
你认为
del a[:]会做什么? -
del a[:] 每次调用函数时都会清空内部列表,以便添加新的元组集
-
是的,它只会清空列表。但它仍然是同一个容器,每个函数调用都在修改同一个对象。所以,最后
List包含对列表a的两个引用。只需将a声明为局部变量。 -
del a[:]没有任何意义。它会创建列表的新副本,然后立即将其删除。 -
@twasbrillig 不,它没有。
del a[:]只是 emptiesa。这是突变,而不是重新分配。