728x90
반응형
Sort
1. 기본적인 리스트 정렬
numbers = [4, 2, 7, 5, 1]
numbers.sort()
print(numbers) # 출력: [1, 2, 4, 5, 7]
list.sort(reverse=True)를 사용하면 역순으로 정렬할 수 있다.
numbers = [4, 2, 7, 5, 1]
numbers.sort(reverse=True)
print(numbers) # 출력: [7, 5, 4, 2, 1]
2. key를 사용한 정렬
words = ['apple', 'banana', 'cherry', 'grape', 'kiwi']
words.sort(key=len)
print(words) # 출력: ['kiwi', 'apple', 'grape', 'banana', 'cherry']
3. 2차원 배열 정렬
matrix = [[2, 3], [1, 4], [4, 1], [3, 2]]
matrix.sort(key=lambda x: x[1])
print(matrix) # 출력: [[4, 1], [2, 3], [3, 2], [1, 4]]
list.sort(key=lambda x: x[1[)// 1번 인덱스로 정렬을 한 것이다.
4. 딕셔너리 정렬
dict_data = {'b': 2, 'a': 1, 'd': 4, 'c': 3}
sorted_data = sorted(dict_data.items(), key=lambda x: x[1])
print(sorted_data) # 출력: [('a', 1), ('b', 2), ('c', 3), ('d', 4)]
딕셔너리를 items()을 이용하여 튜플로 변환한 뒤, sorted() 함수를 이용하여 정렬을 하였다.
sorted()함수는 새로운 리스트를 반환하므로, 원본에 영향을 주지 않는다,
728x90
반응형
'프로그래밍_백준 > Python' 카테고리의 다른 글
Python) 백준 1463번: dp, 1로 만들기 (0) | 2024.09.30 |
---|---|
Pyton) 정렬 함수 사용 및 lambda (0) | 2024.09.29 |
Phthon) 1929번 소수 구하기 (0) | 2023.08.10 |
Python) 10989 수 정렬하기 Counting Sort (계수 정렬) (0) | 2023.08.08 |
Python) 1181번 단어 정렬 (sort함수) (0) | 2023.08.07 |