Login

Search

Learn 🇰🇷
2022.10.02 19:15

4.5 세트(set)

Views 848 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 2262
44 Learn 8.1 Exception handling (try, except) admin 2024.11.17 958
43 Learn 7.1 Class and Instance admin 2024.11.17 1237
42 Learn 6.1 Text file admin 2024.11.17 1132
41 Learn 5.3 Different modules admin 2024.11.17 1196
40 Learn 5.2 Import modules admin 2024.11.17 1192
39 Learn 5.1 What is module? admin 2024.11.17 956
38 Learn 4.5 Set admin 2024.11.17 902
37 Learn 4.4 Dictionary admin 2022.09.29 994
36 Learn 4.3 Tuple admin 2024.11.17 1016
35 Learn 4.2 String and List admin 2024.11.17 1023
34 Learn 4.1 Data types admin 2024.11.17 855
33 Learn 3.4 Lambda admin 2024.11.17 846
32 Learn 3.3 Global and local variables admin 2024.11.17 951
31 Learn 3.2 return statement admin 2022.11.29 993
30 Learn 3.1 Function admin 2022.11.27 896
29 Learn 2.3 Iterative statements using for loop admin 2022.11.26 1024
28 Learn 2.2 if-elif-else statements admin 2022.11.22 894
27 Learn 2.1 Iterative statements using while admin 2022.11.19 996
26 Learn 1.4 Interpreter and Compiler admin 2022.11.05 858
25 Learn 1.3 LIst admin 2022.11.03 977
Board Pagination Prev 1 2 3 Next
/ 3