python
python 인스턴스 클래스가 담겨진 list 특정 변수값으로 정렬하기
이농이능
2018. 4. 18. 18:24
파이썬에서 특정 변수로 클래스를 정렬하고 싶을 때,
클래스에다 def __lt__(self,other) 함수를 넣어서 비교할 때 사용하는 변수를 넣고 리스트를 sorted() 로 이용하면 된다.
사용예시)
class MyClass:
def __init(self,num):
self.num = num
# 다른 인스턴스 변수들
def __lt__(self, other):
return self.num < other.num
클래스가 리스트 형태로
myclass_list 란 이름으로 정렬이 안된 채로 있다고 했을 때,
sorted_myclass = sorted(myclass_list)
하면 끝.