Python中的列表->;输出错误
我试图打印循环中的列表列表,但输出错误! 附加到较大列表的最后一个列表正在重复 我期望的输出:Python中的列表->;输出错误,python,list,Python,List,我试图打印循环中的列表列表,但输出错误! 附加到较大列表的最后一个列表正在重复 我期望的输出: 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():
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
您多次将同一列表(
a
)附加到list
(您可以通过print list[0]看到列表[1]
)。您需要创建多个列表,如下例所示:
l = []
for i in xrange(3):
l.append([i, i+1])
print l
问题在于
dela[:]
语句。代码的其余部分很好。不要这样做,而是在函数开头放置一个空的列表,问题就会消失:
count = 1
#Function that generates some nos. for the list
def func():
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 = []
count = 1
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
你认为dela[:]是做什么的?每次我调用函数时,dela[:]都会清空内部列表,这样就可以添加新的元组集,它只清空列表。但它仍然是同一个容器,每个函数调用都在修改同一个对象。因此,List
最后包含了对Lista
的两个引用。只需将a
声明为局部变量。dela[:]
没有任何意义。它会创建列表的新副本,然后立即将其删除。@twasbrillig不,不会dela[:]
只需清空a
。这是变异,不是重新分配。