Potato
์•ˆ๋…•ํ•˜์„ธ์š”, ๊ฐ์žก๋‹ˆ๋‹ค?๐Ÿฅ” ^___^ ๐Ÿ˜บ github ๋ฐ”๋กœ๊ฐ€๊ธฐ ๐Ÿ‘‰๐Ÿป

potato's Dev Note/Python

[python] ํŒŒ์ด์ฌ ๋ฆฌ์ŠคํŠธ ๋น„๊ตํ•˜๊ธฐ (set ์ž๋ฃŒํ˜• ์ด์šฉํ•˜๊ธฐ!)

๊ฐ์ž ๐Ÿฅ” 2021. 8. 18. 17:26
๋ฐ˜์‘ํ˜•

๋“ค์–ด๊ฐ€๋ฉฐ

์ฝ”๋”ฉํ…Œ์ŠคํŠธ๋ฅผ ์—ฐ์Šตํ•˜๊ณ  ๋‹ค๋ฅธ์‚ฌ๋žŒ๋“ค์˜ ํ’€์ด๋ฅผ ๊ณต๋ถ€ํ•˜๋‹ค ๋ณด๋ฉด ๊ต‰์žฅํžˆ ๊ธฐ์ดˆ์ ์ธ ๋ถ€๋ถ„์—์„œ ์ฝ”๋“œ์˜ ๊ธธ์ด๋ฅผ ์ค„์ด๊ณ , ์‹œ๊ฐ„๋ณต์žก๋„๋ฅผ ์ค„์ผ ์ˆ˜ ์žˆ๋‹ค๋Š” ๊ฒƒ์„ ๋Š๋‚€๋‹ค. ๋”ฐ๋ผ์„œ ์ฝ”๋”ฉํ…Œ์ŠคํŠธ์—์„œ ํ—ท๊ฐˆ๋ฆฌ์ง€ ์•Š๊ณ  ๋Šฅ์ˆ™ํ•˜๊ฒŒ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๋„๋ก set ์ง‘ํ•ฉ์— ๋Œ€ํ•ด์„œ ์ •๋ฆฌํ•ด๋‘์ž!

 

1. ํŒŒ์ด์ฌ ๋ฆฌ์ŠคํŠธ ์ค‘๋ณต ์ œ๊ฑฐํ•˜๊ธฐ

a = [1,2,3,3,3,3,4,5,6,7,3,5,6,7]
a = set(a)
print(a)

# ๋‹ค์‹œ ๋ฆฌ์ŠคํŠธ๋กœ ์‚ฌ์šฉํ•˜๊ณ  ์‹ถ๋‹ค๋ฉด?
a = list(a)
a

set์€ ์ง‘ํ•ฉํ˜•ํƒœ์˜ ์ž๋ฃŒํ˜•์ด๋‹ค. ๋”ฐ๋ผ์„œ ์ค‘๋ณต๋˜๋Š” ๊ฐ’์ด ํ•˜๋‚˜์˜ ์ง‘ํ•ฉ์— ๋“ค์–ด๊ฐˆ ์ˆ˜ ์—†๋Š” ํŠน์„ฑ์„ ์‚ฌ์šฉํ•ด์„œ ๋ฆฌ์ŠคํŠธ ๋‚ด์˜ ์ค‘๋ณต๊ฐ’์„ ๊ฐ„๋‹จํ•˜๊ฒŒ ์ œ์™ธํ•ด์ค„ ์ˆ˜ ์žˆ๋‹ค.

 

2. ํŒŒ์ด์ฌ ๋ฆฌ์ŠคํŠธ ๋น„๊ตํ•˜๊ธฐ (๊ต์ง‘ํ•ฉ, ํ•ฉ์ง‘ํ•ฉ, ์ฐจ์ง‘ํ•ฉ์„ ์ด์šฉํ•˜์ž)

2.1 ๊ต์ง‘ํ•ฉ

a = [1,2,3,4,5]
b = [2,4,999,8,2,1]

intersection = set(a) & set(b)
print(list(intersection))

๋‘ ๊ฐœ์˜ ๊ต์ง‘ํ•ฉ!! ์ฝ”๋”ฉํ…Œ์ŠคํŠธ์—์„œ '๋ณต๊ถŒ ๋‹น์ฒจ๋๋Š”์ง€ ํ™•์ธํ•˜๊ธฐ' ๋“ฑ ๋‘ ๋ฆฌ์ŠคํŠธ๋ฅผ ๋น„๊ตํ•  ๋•Œ ํ•ด๋‹น ๋ฐฉ๋ฒ•์„ ์œ ์šฉํ•˜๊ฒŒ ์‚ฌ์šฉํ•œ๋‹ค. ๊ฒฐ๊ด๊ฐ’์€ list๋กœ ๋ฐ”๊ฟ”์ค˜ ๋ณด์•˜๋‹ค.

 

2.2 ํ•ฉ์ง‘ํ•ฉ

a = [1,2,3,4,5]
b = [2,4,999,8,2,1]

union = set(a) | set(b)
print(union)

 

2.3 ์ฐจ์ง‘ํ•ฉ

a = [1,2,3,4,5]
b = [2,4,999,8,2,1]

differ_a = set(a) - set(b)
differ_b = set(b) - set(a)
print(differ_a)
print(differ_b)

์ด ์ฐจ์ง‘ํ•ฉ ๋•Œ๋ฌธ์— ํ•ด๋‹น ํฌ์ŠคํŒ…์„ ์ž‘์„ฑํ–ˆ๋‹ค. ์ด ๋ฌธ์ œ๋ฅผ ํ’€๋•Œ ๋‚˜๋Š” if๋ฌธ์„ ์ด์šฉํ•ด์„œ ์ฝ”๋“œ๋ฅผ ๊ธธ๊ฒŒ ์ผ์ง€๋งŒ, set์˜ ์ฐจ์ง‘ํ•ฉ์„ ์ด์šฉํ•˜๋ฉด ๋‹จ๋ฒˆ์— ํ•œ์ค„๋กœ ๊ตฌํ•  ์ˆ˜ ์žˆ๋‹ค๋Š” ๊ฒƒ์„ ์•Œ๊ฒŒ ๋˜์—ˆ๋‹ค. ์ฐจ์ง‘ํ•ฉ๋„ ์ฝ”๋”ฉํ…Œ์ŠคํŠธ๋ฅผ ํ’€๋•Œ ์•„์ฃผ ์œ ์šฉํ•˜๊ฒŒ, ์ž์ฃผ ์‚ฌ์šฉ๋˜๋Š” ๊ฒƒ ๊ฐ™๋‹ค!

2.4 ๋Œ€์นญ ์ฐจ์ง‘ํ•ฉ

์œ„์— ์ฐจ์ง‘ํ•ฉ์€ a ๊ธฐ์ค€์—์„œ b๋ฅผ ๋นผ๊ฑฐ๋‚˜ b ๊ธฐ์ค€์—์„œ a๋ฅผ ๋นผ๋Š” ์—ฐ์‚ฐ์„ ์ˆ˜ํ–‰ํ•œ๋‹ค. ํ•˜์ง€๋งŒ ๋‘ ๋ฆฌ์ŠคํŠธ์—์„œ ๊ฒน์น˜๋Š” ๊ฐ’์„ ์ œ์™ธํ•œ '๋ชจ๋“  ๊ฐ’'์„ ๊ตฌํ•ด์•ผํ•  ๋•Œ๋„ ์žˆ์ง€ ์•Š์€๊ฐ€? ์ด๋–„๋Š” ๋ฐ”๋กœ ๋Œ€์นญ ์ฐจ์ง‘ํ•ฉ์„ ์ด์šฉํ•˜๋ฉด๋œ๋‹ค.

a = [1,2,3,4,5]
b = [2,4,999,8,2,1]

differ_all = set(a) ^ set(b)
print(differ_all)

์œ„์— ์ฐจ์ง‘ํ•ฉ๋“ค์˜ ๊ฐ’์ด ํ•œ set๋กœ ํ•ฉ์ณ์ ธ์„œ ๋‚˜์˜จ๋‹ค. 

๋ฐ˜์‘ํ˜•