728x90
반응형
1. 정렬 (sort)
sort()를 사용하면 요소들을 오름차순(ASC)으로 정렬할 수 있습니다.
(단, 문자와 숫자를 섞게되면 TypeError가 발생합니다.)
a = [3, 55, 12, 67, 1, 88, 152, 60]
b = ['test4', 'test2', 'test3', 'test1']
c = [3, 55.5, 12.1, 67, 1.3, 88, 152.6, 60]
a.sort()
b.sort()
c.sort()
print(a) # [1, 3, 12, 55, 60, 67, 88, 152]
print(b) # ['test1', 'test2', 'test3', 'test4']
print(c) # [1.3, 3, 12.1, 55.5, 60, 67, 88, 152.6]
reverse 옵션을 추가하면 내림차순(DECS)로 정렬이 가능하고, key를 이용해서 함수를 옵션으로 넣을 수 있습니다.
a = [3, 55, 12, 67, 1, 88, 152, 60]
b = ['test long', 'test long long', 'test1', 'test2']
c = ['test long', 'test long long', 'test1', 'test2']
a.sort(reverse=True)
b.sort(key=len)
c.sort(key=len, reverse=True)
print(a) # [152, 88, 67, 60, 55, 12, 3, 1]
print(b) # ['test1', 'test2', 'test long', 'test long long']
print(c) # ['test long long', 'test long', 'test1', 'test2']
2. 뒤집기 (reverse)
reverse()는 내림차순으로 정렬이 아닌 현재 상태의 리스트를 뒤집어 줍니다.
정렬이 아니기 때문에 문자와 숫자를 섞더라도 error를 반환하지 않습니다.
a = [3, 55, 12, 67, 1, 88, 152, 60]
b = ['test long', 'test long long', 'test1', 'test2']
c = ['test long', 'test long long', 21, 2200]
a.reverse()
b.reverse()
c.reverse()
print(a) # [60, 152, 88, 1, 67, 12, 55, 3]
print(b) # ['test2', 'test1', 'test long long', 'test long']
print(c) # [2200, 21, 'test long long', 'test long']
728x90
반응형
'[R&D] 프로그래밍 > Python' 카테고리의 다른 글
[Python] 딕셔너리 (dict) method 활용 (feat. 반복문) (0) | 2022.08.05 |
---|---|
[Python] 딕셔너리 (dict) 기본 사용 방법 (0) | 2022.08.04 |
[Python] 파이썬 자료형 정리 (0) | 2022.07.15 |
[Python] 슬라이싱 (slicing) 개념 및 사용 방법 (2) | 2022.07.06 |
[Python] 리스트(list)를 Stack, Queue 처럼 사용하기 - pop (0) | 2022.07.05 |
[Python] 리스트(list) method - copy, count, index (0) | 2022.07.03 |
[Python] 리스트(list) 사용 방법 (0) | 2022.07.01 |
댓글