๋ชฉ์ฐจ
728x90
์์ ๋ณต์ฌ(shallow copy)
๊ฐ์ ์๋ก์ด ๊ฐ์ฒด๋ก ๋ณต์ฌํ ๋ '์ฐธ์กฐ ๊ฐ'๋ง ๋ณต์ฌํ๋ ๋ฐฉ์
1. copy
import copy
a = [1,2,3]
b = a.copy()
a[2] = 2
print(a)
print(b)
ใ
กใ
กใ
กใ
กใ
กใ
กใ
กใ
ก
[1, 2, 2]
[1, 2, 3]
๊ฐ๋ง ๋ณต์ฌ๋ฅผ ํด์ค๋ ๊ฒ์ด๋ฏ๋ก a์ ํ ๋น๋ ๊ฐ์ ๋ฐ๊พธ์ด๋ b์ ๊ฐ์ ๋ณํ๊ฐ ์๋ค!
'b = a'๋ผ๋ ์ฝ๋์ ๋๋น๋๋ ๋ฐฉ์์ด๋ค.
2. [:]
a = [1,2,3]
b = a[:]
a[2] = 2
print(a)
print(b)
ใ
กใ
กใ
กใ
กใ
กใ
กใ
กใ
ก
[1, 2, 2]
[1, 2, 3]
์ธ๋ฑ์ฑ์ ํ์ฉํ์ฌ ์์ ๋ณต์ฌ๋ฅผ ํ๋ ๋ฐฉ๋ฒ๋ ์๋ค.
์ฃผ์
import copy
a = [1,2,3,[4,5,6]]
b = a.copy()
a[3][0] = 2
print(a)
print(b)
ใ
กใ
กใ
กใ
กใ
กใ
กใ
กใ
ก
[1, 2, 3, [2, 5, 6]]
[1, 2, 3, [2, 5, 6]]
'๋ฆฌ์คํธ ์์ ๋ฆฌ์คํธ'๋ copyํจ์๋ฅผ ์ฌ์ฉํ์ฌ๋ ๊ฐ์ ๋ณ๊ฒฝ์ด ์ ์ฉ๋๋ค.
๊น์ ๋ณต์ฌ(deep copy)
์ฐธ์กฐ๊ฐ๋ฟ๋ง ์๋๋ผ ์ฐธ์กฐ ํ์๊น์ง ๋ณต์ฌํ๋ ๋ฐฉ์, ์ ์ฒด๋ณต์ฌ
import copy
a = [1,2,3,[4,5,6]]
b = copy.deepcopy(a)
a[3][0] = 2
print(a)
print(b)
ใ
กใ
กใ
กใ
กใ
กใ
กใ
กใ
ก
[1, 2, 3, [2, 5, 6]]
[1, 2, 3, [4, 5, 6]]
๋ฆฌ์คํธ ์์ ๋ฆฌ์คํธ๋ deepcopyํจ์๋ฅผ ์ฌ์ฉํ์ฌ ๊ฐ์ด ๋ณ๊ฒฝ๋์ง ์๋ ๊ฒ์ ์ ์ ์๋ค.
'๐ | Python > ํ์ด์ฌ ๋ฌธ๋ฒ' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
ํจ์_(1) (0) | 2021.09.19 |
---|---|
๋ฌธ์์ด ํฌ๋งคํ (0) | 2021.09.18 |
๋ฎคํฐ๋ธ(mutable)๊ณผ ์ด๋ฎคํฐ๋ธ(immutable) (0) | 2021.09.13 |
๋ณ์ (0) | 2021.09.13 |
while (0) | 2021.09.06 |
๋๊ธ