[Python] set

Jimin_Noteยท2022๋…„ 5์›” 25์ผ
0

[Python]

๋ชฉ๋ก ๋ณด๊ธฐ
15/34

๐Ÿ“Set

๐Ÿ‘‰List์™€ ์ฐจ์ด์ 

  • list๋Š” ์‚ฝ์ž… ์ˆœ์„œ๋Œ€๋กœ ์ธ๋ฑ์Šค ๋ฒˆํ˜ธ๊ฐ€ ๋ถ€์—ฌ๋˜์–ด ์ˆœ์„œ๋ฅผ ๊ฐ€์ง€์ง€๋งŒ set์€ ์‚ฝ์ž… ์ˆœ์„œ๋Œ€๋กœ ์ €์žฅ๋˜์ง€ ์•Š๋Š”๋‹ค.
    ์ˆœ์„œ๊ฐ€ ์—†์œผ๋ฏ€๋กœ indexing๋„ ์—†๊ธฐ ๋•Œ๋ฌธ์— ๋ช‡๋ฒˆ์งธ ์š”์†Œ๋ฅผ ์ฝ์–ด๋“ค์ผ ์ˆ˜ ์—†๋‹ค.
  • ์š”์†Œ๋ฅผ ์ถ”๊ฐ€ํ•  ๋•Œ set์ด๋ฆ„.append(์š”์†Œ) ํ˜•์‹์ด ์•„๋‹ˆ๋ผ set์ด๋ฆ„.add(์š”์†Œ)๋กœ ์ถ”๊ฐ€ํ•ด์•ผํ•œ๋‹ค.
    ๋งŒ์ผ ์ƒˆ๋กœ ์ €์žฅํ•˜๋ ค๊ณ  ํ•˜๋Š” ์š”์†Œ์™€ ๋™์ผํ•œ ๊ฐ’์˜ ์š”์†Œ๊ฐ€ ์กด์žฌํ•œ๋‹ค๋ฉด ์ƒˆ๋กœ์šด ์š”์†Œ๊ฐ€ ์ด ์ „ ์š”์†Œ๋ฅผ ์น˜ํ™˜(replace)ํ•ฉ๋‹ˆ๋‹ค.

๐Ÿ‘‰Set ์ƒ์„ฑํ•˜๋Š” ๋ฒ•
1. ์ค‘๊ด„ํ˜ธ { } ๋ฅผ ์‚ฌ์šฉํ•˜๋Š” ๋ฐฉ๋ฒ•
2. set() ํ•จ์ˆ˜๋ฅผ ์‚ฌ์šฉํ•˜๋Š” ๋ฐฉ๋ฒ•

set1 = {1, 2, 3}
set2 = set([1, 2, 3])

์œ„์ฒ˜๋Ÿผ set() ํ•จ์ˆ˜๋ฅผ ์‚ฌ์šฉํ•ด์„œ set๋ฅผ ๋งŒ๋“ค๊ธฐ ์œ„ํ•ด์„œ๋Š” list๋ฅผ parameter๋กœ ์ „๋‹ฌํ•ด์•ผ ํ•œ๋‹ค.

์ฆ‰, ๋ณดํ†ต list๋ฅผ set๋กœ ๋ณ€ํ™˜ํ•˜๊ณ  ์‹ถ์„ ๋•Œ ์‚ฌ์šฉ!

๋ชจ๋“  ์‚ฌ๋žŒ๋“ค์˜ ์ฃผ๋ฏผ๋ฒˆํ˜ธ๋Š” ๋ชจ๋‘ ๋‹ค๋ฅด์ง€๋งŒ ๋™๋ช…์ด์ธ์€ ์žˆ์„ ์ˆ˜ ์žˆ๋‹ค.
์—ฌ๊ธฐ์— ๋น„๊ตํ•ด์„œ ์„ค๋ช…ํ•ด๋ณด์ž๋ฉด
'set1' ์ด๋ผ๋Š” ๋งˆ์„์ด ์žˆ๊ณ  ์ด ๋งˆ์„ ์‚ฌ๋žŒ๋“ค์€ ๋ชจ๋‘ ์ด๋ฆ„์ด ์ˆซ์ž๋กœ ๋˜์–ด์žˆ๋‹ค๊ณ  ๊ฐ€์ •ํ•ด๋ณด์ž.
์ด ๋งˆ์„์— ์‚ฌ๋Š” ์ฃผ๋ฏผ๋“ค์€ {1,2,3} ์ด๋ ‡๊ฒŒ ์ด 3๋ช…์ด ์žˆ๊ณ 
์ด ์ค‘ '1'์ด๋ผ๋Š” ์‚ฌ๋žŒ์˜ ์ฃผ๋ฏผ๋ฒˆํ˜ธ๋Š” '1234'๋ผ๊ณ  ํ•˜์ž.
์–ด๋Š ๋‚  ๋™๋ช…์ด์ธ์˜ '1'์ด๋ผ๋Š” ์‚ฌ๋žŒ์ด ์ด์‚ฌ๋ฅผ ์˜ค๊ฒŒ๋˜์—ˆ๋‹ค.์ด ์‚ฌ๋žŒ์˜ ์ฃผ๋ฏผ๋ฒˆํ˜ธ๋Š” '5678'์ด๋‹ค.
์ด ๋งˆ์„์—๋Š” ๋™๋ช…์ด์ธ์ด ์žˆ์„ ์ˆ˜ ์—†๋‹ค๋Š” ๊ทœ์น™์ด ์žˆ๊ธฐ๋•Œ๋ฌธ์—
์ฃผ๋ฏผ๋ฒˆํ˜ธ '1234'์˜ '1'์ด๋ผ๋Š” ์‚ฌ๋žŒ์€ '5678'์˜ '1'๋ผ๋Š” ์‚ฌ๋žŒ์œผ๋กœ ๊ต์ฒด(์น˜ํ™˜)๋œ๋‹ค.

set1 = {1, 2, 3, 1} #{1,2,3,}
print(set1) #{1, 2, 3}
set2  = set([1, 2, 3, 1])
print(set2) #{1, 2, 3}

๐Ÿ‘‰Set์—์„œ ์ƒˆ๋กœ์šด ์š”์†Œ ์ถ”๊ฐ€ํ•˜๊ธฐ

my_set = {1, 2, 3}
my_set.add(4)
print(my_set) #{1, 2, 3, 4}

๐Ÿ‘‰Set์—์„œ ์š”์†Œ ์‚ญ์ œํ•˜๊ธฐ

my_set = {1, 2, 3}
my_set.remove(3)
print(my_set) #{1,2}

๐Ÿ‘‰Look Up
Set์— ์–ด๋– ํ•œ ๊ฐ’์ด ์ด๋ฏธ ํฌํ•จ๋˜์–ด ์žˆ๋Š”์ง€๋ฅผ ์•Œ์•„๋ณด๋Š” ๊ฒƒ

my_set = {1, 2, 3}

if 1 in my_set:
    print("1 is in the set") #1 is in the set

if 4 not in my_set:
    print("4 is not in the set") #4 is not in the set

๐Ÿ‘‰Intersection (๊ต์ง‘ํ•ฉ) & Union (ํ•ฉ์ง‘ํ•ฉ)

set1 = {1, 2, 3, 4, 5, 6}
set2 = {4, 5, 6, 7, 8, 9}

print(set1 & set2) #{4, 5, 6}

print(set1.intersection(set2)) #{4, 5, 6}

print(set1 | set2) #{1, 2, 3, 4, 5, 6, 7, 8, 9}

print(set1.union(set2)) #{1, 2, 3, 4, 5, 6, 7, 8, 9}
profile
Hello. I'm jimin:)

0๊ฐœ์˜ ๋Œ“๊ธ€