๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
๐Ÿš€ Development/Python

[Python] 2์ฐจ์›” ๋ฐฐ์—ด ์„ ์–ธ ๋ฐฉ๋ฒ•

by Jay Din 2023. 9. 20.
728x90
๋ฐ˜์‘ํ˜•
๋ฐ˜์‘ํ˜•

1์ฐจ์› ๋ฐฐ์—ด ์„ ์–ธ

rows = 10
graph = [0] * rows

print(graph)
์‹คํ–‰๊ฒฐ๊ณผ
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

 

2์ฐจ์› ๋ฐฐ์—ด ์„ ์–ธ ISSUE CASE

2์ฐจ์› ๋ฐฐ์—ด ์„ ์–ธ์—์„œ 1์ฐจ์› ๋ฐฐ์—ด์—์„œ ์„ ์–ธํ•œ ๋ฐฉ๋ฒ•๊ณผ ๊ฐ™์ด *์„ ์‚ฌ์šฉํ•˜๋ฉด ๋ฌธ์ œ๊ฐ€ ์ƒ๊น๋‹ˆ๋‹ค.

rows = 10
cols = 5
graph = [[0] * cols] * rows

print(graph)
์‹คํ–‰ ๊ฒฐ๊ณผ
[[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]

 

ํ•˜์ง€๋งŒ ์—ฌ๊ธฐ์„œ ๊ฐ’์„ ๋„ฃ์–ด๋ณด๋ฉด ๋ฌธ์ œ๊ฐ€ ์ƒ๊น๋‹ˆ๋‹ค.

graph[0][0] = 1
[[1, 0, 0, 0, 0], [1, 0, 0, 0, 0], [1, 0, 0, 0, 0], [1, 0, 0, 0, 0], [1, 0, 0, 0, 0], [1, 0, 0, 0, 0], [1, 0, 0, 0, 0], [1, 0, 0, 0, 0], [1, 0, 0, 0, 0], [1, 0, 0, 0, 0]]

graph์˜ 0ํ–‰ 0์—ด์—๋งŒ ๊ฐ’์„ ๋„ฃ์—ˆ๋Š”๋ฐ, graph์˜ ๋ชจ๋“  ํ–‰์˜ 0์—ด์— ๊ฐ’์ด ๋ณ€๊ฒฝ๋˜์—ˆ์Šต๋‹ˆ๋‹ค.

 

728x90

Why?

Python์—์„œ *์—ฐ์‚ฐ์ž๋ฅผ ์ด์šฉํ•ด ๋ฐฐ์—ด์„ ์„ ์–ธํ•˜๊ฒŒ ๋˜๋ฉด, ์–•์€ ๋ณต์‚ฌ(shallow copy)๊ฐ€ ์ง„ํ–‰๋ฉ๋‹ˆ๋‹ค.

์ฆ‰, ๋ฐฐ์—ด ๋‚ด์˜ ์š”์†Œ๋“ค์ด ๊ฐ™์€ ๊ฐ์ฒด๋ฅผ ๊ฐ€๋ฆฌํ‚ค๊ฒŒ ๋˜๋Š” ๊ฒƒ์ž…๋‹ˆ๋‹ค.

๋•Œ๋ฌธ์— 2์ฐจ์› ๋ฐฐ์—ด์„ *์—ฐ์‚ฐ์ž๋กœ ์„ ์–ธํ–ˆ์„ ๋•Œ, ๊ฐ’์„ ๋„ฃ์œผ๋ฉด ๋‹ค๋ฅธ ํ–‰์—๋„ ์˜ํ–ฅ์„ ๋ฏธ์น˜๋Š” ๊ฒƒ์ž…๋‹ˆ๋‹ค.

 

2์ฐจ์› ๋ฐฐ์—ด์„ ์–ด๋–ป๊ฒŒ ์„ ์–ธํ•ด์•ผ ํ• ๊นŒ?

for๋ฌธ์„ ์ด์šฉํ•˜์—ฌ ์„ ์–ธํ•˜๋ฉด ๋ฉ๋‹ˆ๋‹ค.

rows = 10
cols = 5
graph = [[0] * cols for _ in range(rows)]

 

Check

graph[0][0] = 1
[[1, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]

๋ฌธ์ œ์—†์ด ์˜๋„ํ•œ ๋Œ€๋กœ ๋ณ€๊ฒฝ๋œ ๊ฒƒ์„ ํ™•์ธํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

 

๋ฐ˜์‘ํ˜•

 

728x90
๋ฐ˜์‘ํ˜•