일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 |
Tags
- PostgreSQL
- numpy
- evaluation
- GitLab
- Database
- LLM
- CUDA
- Windows
- git
- Flask
- Linux
- AI
- list
- Converting
- format
- Container
- Paper
- Package
- Mac
- Laravel
- Python
- file
- DB
- enV
- pandas
- KAKAO
- docker
- judge
- TORCH
- pytorch
Archives
- Today
- Total
Daily Develope
[Python] 정렬 Sort (Dict, Class) 본문
Dict. 내부 정렬
ㅇ 샘플
samples = {'c':2, 'a':4, 'b':3, 'd':1, 'e':0}
ㅇ 정렬 (숫자/value 기준 오름차순 정렬)
sortedList = dict(sorted(samples.items(), key=lambda s: s[1]))
print(sortedList)
-----
{'e': 0, 'd': 1, 'c': 2, 'b': 3, 'a': 4}
Dict. List 정렬
ㅇ 샘플
samples = [
{"name":"a", "score":50},
{"name":"b", "score":60},
{"name":"c", "score":20},
{"name":"d", "score":70},
{"name":"e", "score":20},
{"name":"e", "score":55},
{"name":"e", "score":90},
{"name":"e", "score":30}
]
ㅇ 정렬 (score값 기준 내림차순 정렬)
sortedDictList = sorted(samples, key=lambda s: s['score'], reverse=True)
print(sortedDictList)
------
[{'name': 'e', 'score': 90}, {'name': 'd', 'score': 70}, {'name': 'b', 'score': 60}, ...]
Class 정렬
: Class의 '__repr__' method 정의 후 sort / sorted method 호출해 사용
1. 클래스 내 "__repr__" method 정의
class Face:
def __init__(self, x, y, gender) -> None:
self._x = x
self._y = y
self._gender = gender
def __repr__(self) -> str:
return repr((self._x, self._y, self._gender))
def __str__(self) -> str:
return "x={}, y={}, gender={}".format(self._x, self._y, self._gender)
2. 사용 (원본 class list 보존 여부에 따라 sort 또는 sorted function 호출)
방법1) sorted, 원본 리스트 보존을 위해 새로운 리스트에 정렬된 리스트 저장
sorted_faceList = sorted(faceList, key=lambda m: m._x)
print(*sorted_faceList, sep='\n')
방법2) sort, 원본 리스트에 정렬된 리스트를 overwrite
faceList.sort(key=lambda m: m._x)
print(*faceList, sep='\n')
'Develope > Python' 카테고리의 다른 글
[Python] 시간 측정 (예제코드) (0) | 2022.06.28 |
---|---|
[Python] Draw Image 이미지 그리기 (0) | 2022.04.11 |
[Python] Kakao API 사용예시 (0) | 2022.04.11 |
[Python] 폴더 및 파일 탐색 (0) | 2022.04.06 |
[Python] Numpy 넘파이 함수 정리 (0) | 2022.04.04 |
Comments