[ํŒŒ์ด์ฌ/python] ์ง‘ํ•ฉ

2021. 4. 5. 17:00

์ง‘ํ•ฉ์€ set์„ ์‚ฌ์šฉํ•ด ๋งŒ๋“ค ์ˆ˜ ์žˆ๋‹ค.

์ง‘ํ•ฉ์€ ์ค‘๋ณต์„ ํ—ˆ์šฉํ•˜์ง€ ์•Š๊ณ  ์ˆœ์„œ๊ฐ€ ์—†๋‹ค.

๊ทธ๋ ‡๊ธฐ ๋•Œ๋ฌธ์— ์ธ๋ฑ์Šค๊ฐ€ ์—†์–ด ์ธ๋ฑ์‹ฑ์„ ํ†ตํ•ด ๊ฐ’์„ ์–ป๊ธฐ ์œ„ํ•ด์„œ๋Š” ๋ฆฌ์ŠคํŠธ๋‚˜ ํŠœํ”Œ๋กœ ๋ณ€ํ™˜ํ•ด์•ผ ํ•œ๋‹ค.

s = set()
>>> {}

s = set([1,2,3])
>>> {1, 2, 3}

s = set("hello")
>>> {'e', 'h', 'l', 'o'}

์ง‘ํ•ฉ์— ๊ฐ’ 1๊ฐœ ์ถ”๊ฐ€, ์—ฌ๋Ÿฌ๊ฐœ ์ถ”๊ฐ€, ์ œ๊ฑฐ ๋“ฑ์€ ๋‹ค์Œ๊ณผ ๊ฐ™์ด ๊ตฌํ˜„ํ•  ์ˆ˜ ์žˆ๋‹ค.

s = set([1, 2, 3])

# ๊ฐ’ ํ•˜๋‚˜ ์ถ”๊ฐ€
s.add(4)
>>> {1, 2, 3, 4}

# ๊ฐ’ ์—ฌ๋Ÿฌ๊ฐœ ์ถ”๊ฐ€
s.update([4, 5])
>>> {1, 2, 3, 4, 5}

# ํŠน์ • ๊ฐ’ ์ œ๊ฑฐ
s.remove(3)
>>> {1, 2}

 

set ์ž๋ฃŒํ˜•์„ ์œ ์šฉํ•˜๊ฒŒ ์‚ฌ์šฉํ•˜๋Š” ๊ฒฝ์šฐ๋Š” ๊ต์ง‘ํ•ฉ, ํ•ฉ์ง‘ํ•ฉ, ์ฐจ์ง‘ํ•ฉ์„ ๊ตฌํ•  ๋•Œ์ด๋‹ค.

๊ธฐํ˜ธ๋ฅผ ์ด์šฉํ•˜์—ฌ ๊ฐ„๋‹จํ•˜๊ฒŒ ๊ตฌํ•  ์ˆ˜ ์žˆ๋‹ค.

s1 = set([1, 2, 3, 4, 5])
s2 = set([3, 4, 5, 6, 7]}

#๊ต์ง‘ํ•ฉ
s1 & s2
s1.intersection(s2)
>>> {3, 4, 5}

#ํ•ฉ์ง‘ํ•ฉ
s1 | s2
s1.union(s2)
>>> {1, 2, 3, 4, 5, 6, 7}

#์ฐจ์ง‘ํ•ฉ
s1 - s2
s1.difference(s2)
>>> {1, 2}

 

728x90

BELATED ARTICLES

more