IT story

파이썬은 여러 변수를 같은 값으로 할당합니까?

hot-time 2020. 7. 28. 07:52
반응형

파이썬은 여러 변수를 같은 값으로 할당합니까? 행동 목록


변수를 초기화하기 위해 아래에 표시된 것처럼 여러 대입을 사용하려고했지만 동작에 혼란스러워서 값 목록을 별도로 다시 할당 할 것으로 예상합니다. 전과 같이 b [0]과 c [0]이 0임을 의미합니다.

a=b=c=[0,3,5]
a[0]=1
print(a)
print(b)
print(c)

결과 : [1, 3, 5] [1, 3, 5] [1, 3, 5]

그 맞습니까? 여러 과제에 무엇을 사용해야합니까? 이것과 다른 점은 무엇입니까?

d=e=f=3
e=4
print('f:',f)
print('e:',e)

결과 : ( 'f :', 3) ( 'e :', 4)


C / Java / etc의 언어에서 Python으로오고 있다면 a"가변"이라고 생각하지 않고 "이름"으로 생각하기 시작하는 것이 도움이 될 수 있습니다 .

a, bc값이 같은 변수가 아닙니다. 그들은 동일한 동일한 값을 위해 다른 이름입니다. 변수에는 유형, ID, 주소 및 모든 종류의 것들이 있습니다.

이름은 그 중 하나도 없습니다. 값은 물론, 할, 당신은 같은 값의 이름을 많이 할 수 있습니다.

Notorious B.I.G.핫도그 를주고 * 핫도그 Biggie SmallsChris Wallace가지고 있다면. 첫 번째 요소 a를 1로 변경하면 b의 첫 번째 요소 c는 1입니다.

두 개의 이름이 같은 객체를 명명하는지 알고 싶다면 is연산자를 사용하십시오 .

>>> a=b=c=[0,3,5]
>>> a is b
True

그런 다음 묻습니다.

이것과 다른 점은 무엇입니까?

d=e=f=3
e=4
print('f:',f)
print('e:',e)

여기에서 이름 e을 값으로 리 바인딩합니다 4. 즉, 이름에 영향을주지 않습니다 df어떤 식 으로든한다.

이전 버전에서는에 할당 a[0]하지 않고에 할당 했습니다 a. 따라서의 관점에서 a[0]리 바인딩하는 것입니다 a[0]. 그러나의 관점에서는 a그 위치를 변경하고 있습니다.

id객체의 아이덴티티를 나타내는 고유 번호를 제공 하는 함수를 사용하면 어떤 객체가 is도움이 수 없는지 정확하게 알 수 있습니다.

>>> a=b=c=[0,3,5]
>>> id(a)
4473392520
>>> id(b)
4473392520
>>> id(a[0])
4297261120
>>> id(b[0])
4297261120

>>> a[0] = 1
>>> id(a)
4473392520
>>> id(b)
4473392520
>>> id(a[0])
4297261216
>>> id(b[0])
4297261216

공지 사항 a[0]4297261120로 변경되었습니다 4297261216는 - 지금 다른 값의 이름입니다. 그리고 b[0]이제 같은 새로운 가치의 이름이기도합니다. 그 때문에 a그리고 b여전히 같은 개체의 이름을 지정합니다.


Under the covers, a[0]=1 is actually calling a method on the list object. (It's equivalent to a.__setitem__(0, 1).) So, it's not really rebinding anything at all. It's like calling my_object.set_something(1). Sure, likely the object is rebinding an instance attribute in order to implement this method, but that's not what's important; what's important is that you're not assigning anything, you're just mutating the object. And it's the same with a[0]=1.


user570826 asked:

What if we have, a = b = c = 10

That's exactly the same situation as a = b = c = [1, 2, 3]: you have three names for the same value.

But in this case, the value is an int, and ints are immutable. In either case, you can rebind a to a different value (e.g., a = "Now I'm a string!"), but the won't affect the original value, which b and c will still be names for. The difference is that with a list, you can change the value [1, 2, 3] into [1, 2, 3, 4] by doing, e.g., a.append(4); since that's actually changing the value that b and c are names for, b will now b [1, 2, 3, 4]. There's no way to change the value 10 into anything else. 10 is 10 forever, just like Claudia the vampire is 5 forever (at least until she's replaced by Kirsten Dunst).


* Warning: Do not give Notorious B.I.G. a hot dog. Gangsta rap zombies should never be fed after midnight.


Cough cough

>>> a,b,c = (1,2,3)
>>> a
1
>>> b
2
>>> c
3
>>> a,b,c = ({'test':'a'},{'test':'b'},{'test':'c'})
>>> a
{'test': 'a'}
>>> b
{'test': 'b'}
>>> c
{'test': 'c'}
>>> 

Yes, that's the expected behavior. a, b and c are all set as labels for the same list. If you want three different lists, you need to assign them individually. You can either repeat the explicit list, or use one of the numerous ways to copy a list:

b = a[:] # this does a shallow copy, which is good enough for this case
import copy
c = copy.deepcopy(a) # this does a deep copy, which matters if the list contains mutable objects

Assignment statements in Python do not copy objects - they bind the the name to an object, and an object can have as many labels as you set. In your first edit, changing a[0], you're updating one element of the single list that a, b, and c all refer to. In your second, changing e, you're switching e to be a label for a different object (4 instead of 3).


In python, everything is an object, also "simple" variables types (int, float, etc..).

When you changes a variable value, you actually changes it's pointer, and if you compares between two variables it's compares their pointers. (To be clear, pointer is the address in physical computer memory where a variable is stored).

As a result, when you changes an inner variable value, you changes it's value in the memory and it's affects all the variables that point to this address.

For your example, when you do:

a = b =  5 

This means that a and b points to the same address in memory that contains the value 5, but when you do:

a = 6

It's not affect b because a is now points to another memory location that contains 6 and b still points to the memory address that contains 5.

But, when you do:

a = b = [1,2,3]

a and b, again, points to the same location but the difference is that if you change the one of the list values:

a[0] = 2

It's changes the value of the memory that a is points on, but a is still points to the same address as b, and as a result, b changes as well.


You can use id(name) to check if two names represent the same object:

>>> a = b = c = [0, 3, 5]
>>> print(id(a), id(b), id(c))
46268488 46268488 46268488

Lists are mutable; it means you can change the value in place without creating a new object. However, it depends on how you change the value:

>>> a[0] = 1
>>> print(id(a), id(b), id(c))
46268488 46268488 46268488
>>> print(a, b, c)
[1, 3, 5] [1, 3, 5] [1, 3, 5]

If you assign a new list to a, then its id will change, so it won't affect b and c's values:

>>> a = [1, 8, 5]
>>> print(id(a), id(b), id(c))
139423880 46268488 46268488
>>> print(a, b, c)
[1, 8, 5] [1, 3, 5] [1, 3, 5]

Integers are immutable, so you cannot change the value without creating a new object:

>>> x = y = z = 1
>>> print(id(x), id(y), id(z))
507081216 507081216 507081216
>>> x = 2
>>> print(id(x), id(y), id(z))
507081248 507081216 507081216
>>> print(x, y, z)
2 1 1

in your first example a = b = c = [1, 2, 3] you are really saying:

 'a' is the same as 'b', is the same as 'c' and they are all [1, 2, 3]

If you want to set 'a' equal to 1, 'b' equal to '2' and 'c' equal to 3, try this:

a, b, c = [1, 2, 3]

print(a)
--> 1
print(b)
--> 2
print(c)
--> 3

Hope this helps!


What you need is this:

a, b, c = [0,3,5] # Unpack the list, now a, b, and c are ints
a = 1             # `a` did equal 0, not [0,3,5]
print(a)
print(b)
print(c)

Simply put, in the first case, you are assigning multiple names to a list. Only one copy of list is created in memory and all names refer to that location. So changing the list using any of the names will actually modify the list in memory.

In the second case, multiple copies of same value are created in memory. So each copy is independent of one another.


The code that does what I need could be this:

# test

aux=[[0 for n in range(3)] for i in range(4)]
print('aux:',aux)

# initialization

a,b,c,d=[[0 for n in range(3)] for i in range(4)]

# changing values

a[0]=1
d[2]=5
print('a:',a)
print('b:',b)
print('c:',c)
print('d:',d)

Result:

('aux:', [[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]])
('a:', [1, 0, 0])
('b:', [0, 0, 0])
('c:', [0, 0, 0])
('d:', [0, 0, 5])

참고URL : https://stackoverflow.com/questions/16348815/python-assigning-multiple-variables-to-same-value-list-behavior

반응형