【问题标题】:Why python print [...] [duplicate]为什么 python 打印 [...] [重复]
【发布时间】:2016-08-18 07:09:21
【问题描述】:

有人能解释一下为什么我的 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)

【问题讨论】:

  • 这是因为列表引用了自身。试试这个:x = [1,2,3] 然后x[2] = x 然后print(x)print(x[2])print(x[2][2])print(x[2][2][1])

标签: python python-3.x


【解决方案1】:

这是因为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

【讨论】:

    猜你喜欢
    • 2023-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多