파이썬에서 Set(집합) 자료구조를 튜플(Tuple)로 변환하거나, 반대로 튜플을 Set으로 변환해야 할 때는 내장 함수인 tuple()과 set() 메서드를 사용하면 됩니다.
아래 예제를 통해 실제 동작 과정을 살펴보겠습니다.
예제 코드
my_set = {'ab', 'cd', 'ef', 'g', 'h', 's', 'v'}
print("The type is : ")
print(type(my_set), " ", my_set)
print("Converting a set into a tuple")
my_tuple = tuple(my_set)
print("The type is : ")
print(type(my_tuple), " ", my_tuple)
my_tuple = ('ab', 'cd', 'ef', 'g', 'h', 's', 'v')
print("The tuple is:")
print(my_tuple)
print(type(my_tuple), " ", my_tuple)
print("Converting tuple to set")
my_set = set(my_tuple)
print(type(my_set), " ", my_set)실행 결과
The type is :
<class 'set'> {'ef', 'g', 'h', 's', 'ab', 'v', 'cd'}
Converting a set into a tuple
The type is :
<class 'tuple'> ('ef', 'g', 'h', 's', 'ab', 'v', 'cd')
The tuple is:
('ab', 'cd', 'ef', 'g', 'h', 's', 'v')
<class 'tuple'> ('ab', 'cd', 'ef', 'g', 'h', 's', 'v')
Converting tuple to set
<class 'set'> {'ef', 'g', 'h', 's', 'ab', 'v', 'cd'}코드 설명
먼저 문자열 요소들로 이루어진 하나의 Set을 정의하고 콘솔에 출력합니다.
type()메서드를 사용하여 해당 데이터 구조의 자료형을 확인합니다.tuple()메서드를 호출하여 Set을 튜플로 변환합니다.변환된 객체의 자료형을 다시
type()메서드로 확인합니다.새로운 튜플을 직접 정의한 뒤, 이번에는
set()메서드를 사용하여 튜플을 다시 Set으로 변환합니다.마지막으로 변환된 결과의 자료형과 값을 콘솔에 출력합니다.
참고 사항
Set은 순서가 없는(unordered) 자료구조이기 때문에, Set을 튜플로 변환할 때 요소들의 순서는 실행 시점마다 달라질 수 있습니다. 따라서 요소의 순서가 중요한 경우에는 변환 후 정렬 작업을 추가하는 것이 좋습니다.