我试图从循环中打印列表列表,但输出错误! 附加到较大列表的最后一个列表是重复。
输出我期待:
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
答案 0 :(得分:1)
您将相同的列表(a
)多次附加到List
(您可以使用print List[0] is List[1]
查看)。您需要创建多个列表,如下例所示:
l = []
for i in xrange(3):
l.append([i, i+1])
print l
答案 1 :(得分:1)
问题在于del a[:]
语句。剩下的代码很好。而不是这样做,在函数的开头放一个空的a
列表,问题就消失了:
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