티스토리 뷰

공부

[Python] union, intersection, difference

승가비 2022. 3. 11. 17:10
728x90

1 테스트 환경

  • lst1의 원소는 A, B, C, D
  • lst2의 원소는 C, D, E, F
  • 데이터 입력
Python
 Copy
lst1 = ['A', 'B', 'C', 'D']
lst2 = ['C', 'D', 'E', 'F']

2 합집합

Python
CPU
0.0s
MEM
8M
0.0s
 
 Copy
lst1 = ['A', 'B', 'C', 'D']
lst2 = ['C', 'D', 'E', 'F']
union = list(set(lst1) | set(lst2))
print( union ) # ['C', 'F', 'A', 'E', 'B', 'D']
union = list(set().union(lst1,lst2))
print( union ) # ['C', 'F', 'A', 'E', 'B', 'D']
['F', 'C', 'E', 'D', 'A', 'B']
['F', 'C', 'E', 'D', 'A', 'B']

3 교집합

Python
CPU
0.0s
MEM
8M
0.0s
 
 Copy
lst1 = ['A', 'B', 'C', 'D']
lst2 = ['C', 'D', 'E', 'F']
intersection = list(set(lst1) & set(lst2))
print( intersection ) # ['C', 'D']
intersection = list(set(lst1).intersection(lst2))
print( intersection ) # ['C', 'D']
['D', 'C']
['D', 'C']

4 차집합

Python
CPU
0.0s
MEM
8M
0.0s
 
 Copy
lst1 = ['A', 'B', 'C', 'D']
lst2 = ['C', 'D', 'E', 'F']
complement = list(set(lst1) - set(lst2))
print( complement ) # ['B', 'A']
complement = list(set(lst1).difference(lst2))
print( complement ) # ['A', 'B']
['A', 'B']
['A', 'B']

5 대칭차집합

Python
CPU
0.0s
MEM
8M
0.0s
 
 Copy
lst1 = ['A', 'B', 'C', 'D']
lst2 = ['C', 'D', 'E', 'F']
sym_diff = list(set(lst1) ^ set(lst2))
print( sym_diff ) # ['F', 'E', 'A', 'B']
sym_diff = list(set(lst1).symmetric_difference(lst2))
print( sym_diff ) # ['F', 'E', 'A', 'B']
['F', 'E', 'B', 'A']
['F', 'E', 'B', 'A']

6 종합 코드

Python
CPU
0.0s
MEM
8M
0.0s
 
 Copy
lst1 = ['A', 'B', 'C', 'D']
lst2 = ['C', 'D', 'E', 'F']
union = list(set(lst1) | set(lst2))
print( union ) # ['D', 'F', 'E', 'B', 'A', 'C']
union = list(set().union(lst1,lst2))
print( union ) # ['D', 'F', 'E', 'B', 'A', 'C']

intersection = list(set(lst1) & set(lst2))
print( intersection ) # ['C', 'D']
intersection = list(set(lst1).intersection(lst2))
print( intersection ) # ['C', 'D']

complement = list(set(lst1) - set(lst2))
print( complement ) # ['A', 'B']
complement = list(set(lst1).difference(lst2))
print( complement ) # ['B', 'A']

sym_diff = list(set(lst1) ^ set(lst2))
print( sym_diff ) # ['A', 'E', 'B', 'F']
sym_diff = list(set(lst1).symmetric_difference(lst2))
print( sym_diff ) # ['A', 'E', 'B', 'F']
['C', 'F', 'A', 'D', 'B', 'E']
['C', 'F', 'A', 'D', 'B', 'E']
['D', 'C']
['D', 'C']
['B', 'A']
['B', 'A']
['F', 'A', 'B', 'E']
['F', 'A', 'B', 'E']

https://zetawiki.com/wiki/Python_%EB%A6%AC%EC%8A%A4%ED%8A%B8_%ED%95%A9%EC%A7%91%ED%95%A9,_%EA%B5%90%EC%A7%91%ED%95%A9,_%EC%B0%A8%EC%A7%91%ED%95%A9,_%EB%8C%80%EC%B9%AD%EC%B0%A8

 

Python 리스트 합집합, 교집합, 차집합, 대칭차 - 제타위키

다음 문자열 포함...

zetawiki.com

 

728x90
댓글
댓글쓰기 폼