누군가가 왜 내 파이썬 코드가 이것을 인쇄하는지 설명 할 수 있습니까? [...] 그것은 무엇을 의미합니까? 감사합니다
내 코드 :
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)
이것은 다음을 수행 할 때 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
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다