sorted() 함수 사용
이 단계에서는 원래 리스트를 수정하지 않고 비교를 위해 sorted() 함수를 사용하는 방법을 배우게 됩니다. sorted() 함수는 반복 가능한 객체에서 새로운 정렬된 리스트를 반환하는 반면, .sort() 메서드는 리스트를 제자리에서 정렬합니다. 이는 원래 리스트를 그대로 유지하려는 경우에 유용합니다.
~/project 디렉토리에서 convert_to_set.py 파일을 계속 사용해 보겠습니다. sorted()를 사용하고 원래 리스트와 비교하도록 코드를 수정하겠습니다.
## Create a list with duplicate elements
my_list = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]
## Convert the list to a set to remove duplicates
my_set = set(my_list)
## Convert the set back to a list
my_list_from_set = list(my_set)
## Use sorted() to get a new sorted list
sorted_list = sorted(my_list_from_set)
## Print the original list from set
print("Original list from set:", my_list_from_set)
## Print the sorted list
print("Sorted list:", sorted_list)
## Check if the original list is equal to the sorted list
if my_list_from_set == sorted_list:
print("The original list is sorted.")
else:
print("The original list is not sorted.")
이제 Python 스크립트를 실행해 보겠습니다. 터미널을 열고 ~/project 디렉토리로 이동합니다.
cd ~/project
그런 다음, python 명령을 사용하여 스크립트를 실행합니다.
python convert_to_set.py
다음과 유사한 출력을 볼 수 있습니다.
Original list from set: [1, 2, 3, 4, 5, 6, 9]
Sorted list: [1, 2, 3, 4, 5, 6, 9]
The original list is sorted.
이 경우, 집합에서 얻은 원래 리스트가 이미 정렬되어 있었습니다. 처음에 정렬되지 않도록 원래 리스트를 수정해 보겠습니다.
## Create a list with duplicate elements
my_list = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]
## Convert the list to a set to remove duplicates
my_set = set(my_list)
## Convert the set back to a list
my_list_from_set = list(my_set)
## Shuffle the list to make sure it's not sorted
import random
random.shuffle(my_list_from_set)
## Use sorted() to get a new sorted list
sorted_list = sorted(my_list_from_set)
## Print the original list from set
print("Original list from set:", my_list_from_set)
## Print the sorted list
print("Sorted list:", sorted_list)
## Check if the original list is equal to the sorted list
if my_list_from_set == sorted_list:
print("The original list is sorted.")
else:
print("The original list is not sorted.")
스크립트를 다시 실행합니다.
python convert_to_set.py
다음과 유사한 출력을 볼 수 있습니다.
Original list from set: [9, 2, 4, 5, 6, 1, 3]
Sorted list: [1, 2, 3, 4, 5, 6, 9]
The original list is not sorted.
이제 원래 리스트가 섞여 있고, sorted() 함수는 비교를 위해 정렬된 버전을 제공하여 원래 리스트가 변경되지 않음을 보여줍니다.