Python 에서 집합을 리스트로 변환했을 때 정렬되었는지 확인하는 방법

PythonBeginner
지금 연습하기

소개

이 랩에서는 Python 에서 집합 (set) 을 리스트로 변환했을 때 정렬된 리스트가 되는지 확인하는 방법을 배우게 됩니다. 이 랩은 중복을 제거하기 위해 리스트에서 집합으로 변환하는 과정을 살펴보고, list() 함수를 사용하여 집합을 다시 리스트로 변환하는 방법을 보여줍니다.

그런 다음, 결과 리스트가 자체의 정렬된 버전과 비교하여 정렬되었는지 확인하는 방법을 배우게 됩니다. 여기에는 리스트를 집합으로 변환하고, 결과 집합을 출력하고, 집합을 다시 리스트로 변환하고, 마지막으로 리스트가 정렬되었는지 확인하는 메서드를 구현하는 Python 스크립트를 만드는 작업이 포함됩니다.

집합 변환 탐색

이 단계에서는 Python 에서 리스트를 집합으로 변환하는 방법을 배우게 됩니다. 집합은 고유한 요소들의 정렬되지 않은 컬렉션입니다. 즉, 집합은 중복된 값을 포함할 수 없습니다. 리스트를 집합으로 변환하는 것은 리스트에서 중복된 요소를 제거하는 유용한 방법입니다.

먼저, VS Code 편집기를 사용하여 ~/project 디렉토리에 convert_to_set.py라는 Python 파일을 생성해 보겠습니다.

## Create a list with duplicate elements
my_list = [1, 2, 2, 3, 4, 4, 5]

## Convert the list to a set
my_set = set(my_list)

## Print the set
print(my_set)

이제 Python 스크립트를 실행해 보겠습니다. 터미널을 열고 ~/project 디렉토리로 이동합니다.

cd ~/project

그런 다음, python 명령을 사용하여 스크립트를 실행합니다.

python convert_to_set.py

다음과 같은 출력을 볼 수 있습니다.

{1, 2, 3, 4, 5}

보시다시피, 중복된 요소가 제거되었고 집합은 고유한 값만 포함합니다.

문자열을 사용하여 다른 예제를 시도해 보겠습니다.

## Create a list of strings with duplicates
string_list = ["apple", "banana", "apple", "orange", "banana"]

## Convert the list to a set
string_set = set(string_list)

## Print the set
print(string_set)

convert_to_set.py에 변경 사항을 저장하고 스크립트를 다시 실행합니다.

python convert_to_set.py

출력은 다음과 같습니다.

{'orange', 'banana', 'apple'}

집합은 정렬되지 않으므로 집합의 요소 순서가 원래 리스트와 다를 수 있습니다.

리스트로 변환 및 정렬 확인

이 단계에서는 집합을 다시 리스트로 변환한 다음 리스트가 정렬되었는지 확인하는 방법을 배우게 됩니다. 여기에는 list() 함수를 사용하여 집합을 변환하고 정렬된 리스트를 원래 리스트와 비교하는 작업이 포함됩니다.

~/project 디렉토리에서 convert_to_set.py 파일을 계속 사용해 보겠습니다. 집합을 다시 리스트로 변환한 다음 정렬하는 코드를 추가하겠습니다.

## 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)

## Print the list obtained from the set
print("List from set:", my_list_from_set)

## Sort the list
my_list_from_set.sort()

## Print the sorted list
print("Sorted list:", my_list_from_set)

이제 Python 스크립트를 실행해 보겠습니다. 터미널을 열고 ~/project 디렉토리로 이동합니다.

cd ~/project

그런 다음, python 명령을 사용하여 스크립트를 실행합니다.

python convert_to_set.py

다음과 유사한 출력을 볼 수 있습니다.

List from set: [1, 2, 3, 4, 5, 6, 9]
Sorted list: [1, 2, 3, 4, 5, 6, 9]

첫 번째 줄은 집합에서 생성된 리스트를 보여주며, 고유한 요소를 포함하지만 원래 순서대로 정렬되지 않을 수 있습니다. 두 번째 줄은 정렬된 리스트를 보여줍니다.

이제 원래 리스트 (중복이 제거되고 리스트로 변환됨) 가 정렬되었는지 확인하는 검사를 추가해 보겠습니다.

## 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)

## Sort the list
sorted_list = sorted(my_list_from_set)

## Check if the list is sorted
if my_list_from_set == sorted_list:
    print("The list is already sorted.")
else:
    print("The list is not sorted.")

## Print the sorted list
print("Sorted list:", sorted_list)

스크립트를 다시 실행합니다.

python convert_to_set.py

다음과 유사한 출력을 볼 수 있습니다.

The list is not sorted.
Sorted list: [1, 2, 3, 4, 5, 6, 9]

이는 집합에서 얻은 리스트가 처음에 정렬되지 않았으며, sorted() 함수를 사용하여 정렬된 버전을 생성했음을 나타냅니다.

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() 함수는 비교를 위해 정렬된 버전을 제공하여 원래 리스트가 변경되지 않음을 보여줍니다.

요약

이 Lab 에서는 Python 에서 리스트를 집합 (set) 으로 변환하여 중복 요소를 효과적으로 제거하는 방법을 배웠습니다. 집합은 순서가 없는 컬렉션이므로 변환 중에 요소의 순서가 변경될 수 있습니다.

또한 집합을 다시 리스트로 변환하고 결과 리스트가 정렬되었는지 확인하는 방법을 배우기 시작했습니다. 여기에는 list() 함수를 사용하고 정렬된 리스트를 원래 리스트와 비교하는 작업이 포함됩니다.