Login

Search

Learn 🇰🇷
2022.10.02 19:15

4.5 세트(set)

Views 192 Votes 0 Comment 0

이번에는 ‘집합’을 표현하는 세트(set)를 좀 더 알아보겠습니다.

과일을 나타내는 fruits 세트를 만들어보겠습니다냠~

>>> fruits = {'apple', 'banana', 'orange

  

 

사과, 바나나, 오렌지를 원소로 갖는 fruits 세트를 만들었습니다. 이와 같이 세트는 중괄호({})를 사용합니다.

아차, 맛있는 망고를 빠뜨렸네요. add()로 추가할게요.

>>> fruits.add('mango')
>>> fruits
{'orange', 'apple', 'mango', 'banana'}

  

 

이번에는 회사 이름을 나타내는 집합을 만들어볼까요?

>>> companies = set()

  

 

회사 이름이 떠오르지 않아서 일단 set()로 빈 세트를 만들었습니다. 아, 생각 났어요.

>>> companies = {'apple', 'microsoft', 'google'

  

 

이제 fruits와 companies 세트를 만들었습니다. 타입을 확인해볼까요?

>>> type(fruits)
<class 'set'>
>>> type(companies)
<class 'set'>

  

 

세트를 이용해 아래와 같이 집합 연산을 사용할 수 있습니다.

>>> fruits & companies           
{'apple'}
>>> fruits | companies    
{'apple', 'mango', 'microsoft', 'orange', 'google', 'banana'}

  

 

아래와 같이 여러 세트를 리스트에 담은 뒤 set의 메서드를 쓸 수도 있습니다.

>>> list_of_sets = [fruits, companies]
>>> set.intersection(*list_of_sets)  
{'apple'}
>>> set.union(*list_of_sets)  # 합집합
{'google', 'apple', 'banana', 'mango', 'microsoft', 'orange'}

  

 

apple은 fruits에도 속하고 companies에도 속하는데, 위 합집합의 결과에 한 번만 나오는 것을 볼 수 있습니다. 이와 같이 세트는 중복 원소를 갖지 않습니다. 또, 원소의 순서가 유지되지 않는 특징도 있습니다.

>>> alphabet = list('google')
>>> alphabet
['g', 'o', 'o', 'g', 'l', 'e']
>>> set(alphabet)
{'e', 'o', 'g', 'l'}

  

 

아참, 집합끼리 뺄셈도 할 수 있어요!

>>> S1 = {1, 2, 3, 4, 5, 6, 7}
>>> S2 = {3, 6, 9}
>>> S1 - S2
{1, 2, 4, 5, 7} 

  

 


List of Articles
No. Subject Author Date Views
Notice Learn What is Python? admin 2024.10.19 448
44 Learn 8.1 Exception handling (try, except) admin 2024.11.17 277
43 Learn 7.1 Class and Instance admin 2024.11.17 280
42 Learn 6.1 Text file admin 2024.11.17 273
41 Learn 5.3 Different modules admin 2024.11.17 290
40 Learn 5.2 Import modules admin 2024.11.17 286
39 Learn 5.1 What is module? admin 2024.11.17 177
38 Learn 4.5 Set admin 2024.11.17 184
37 Learn 4.4 Dictionary admin 2022.09.29 177
36 Learn 4.3 Tuple admin 2024.11.17 193
35 Learn 4.2 String and List admin 2024.11.17 188
34 Learn 4.1 Data types admin 2024.11.17 184
33 Learn 3.4 Lambda admin 2024.11.17 179
32 Learn 3.3 Global and local variables admin 2024.11.17 190
31 Learn 3.2 return statement admin 2022.11.29 187
30 Learn 3.1 Function admin 2022.11.27 197
29 Learn 2.3 Iterative statements using for loop admin 2022.11.26 179
28 Learn 2.2 if-elif-else statements admin 2022.11.22 176
27 Learn 2.1 Iterative statements using while admin 2022.11.19 196
26 Learn 1.4 Interpreter and Compiler admin 2022.11.05 184
25 Learn 1.3 LIst admin 2022.11.03 196
Board Pagination Prev 1 2 3 Next
/ 3