2016-08-18 121 views
-1

有人可以解释我为什么我的Python代码打印这个[...]是什么意思? 谢谢为什么python打印[...]

我的代码:

def foo(x,y): 
    x[0]= y[1] 
    x,y=y,x 
    return x+y 
z=[1,2] 
z2=[z,z] 
t=foo(z,z2) 
print(z) 
print(z2) 
print(t) 
+0

这是因为列表的引用本身。试试这个:'x = [1,2,3]'然后'x [2] = x'然后'print(x)'''print(x [2])'''print(x [2] [2 ])','print(x [2] [2] [1])'' –

回答

0

这是因为z名单在[0]位置引用本身,当你这样做:

def foo(x,y): 
    x[0]= y[1] 
    x,y=y,x 
    return x+y 
z=[1,2] 
#Here you have created a list containing 1,2 
z2=[z,z] 
#here is not creating two lists in itself, but it is referencing z itself(sort of like pointer), you can verify this by: 
In [21]: id(z2[0]) 
Out[21]: 57909496 
In [22]: id(z2[1]) 
Out[22]: 57909496 
#see here both the location have same objects 
t=foo(z,z2) 
#so when you call foo and do x[0]= y[1], what actually happens is 
# z[0] = z2[0] , which is z itself 
# which sort of creates a recursive list 
print(z) 
print(z2) 
print(t) 
#you can test this by 
In [17]: z[0] 
Out[17]: [[...], 2] 
In [18]: z[0][0] 
Out[18]: [[...], 2] 
In [19]: z[0][0][0] 
Out[19]: [[...], 2] 
In [20]: z[0][0][0][0] 
Out[20]: [[...], 2] 
#you can carry on forever like this, but since it is referencing itself, it wont see end of it