본문 바로가기
[R&D] 프로그래밍/Python

[Python] 리스트(list) 정렬하기

by Geuni 2022. 7. 2. 09:49
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
반응형

댓글