파이썬 다중정렬 orderBy()

(파이썬 orderBy()에서 넘어옴)

1 개요[ | ]

파이썬 다중정렬 orderBy()
from pprint import pprint

def orderBy(by, ascending=[]):
  class K:
    def __init__(self, o, *args): self.o = o
    def __lt__(self, other):
      for i, key in enumerate(by):
        asc = ascending[i] if i < len(ascending) else True
        if self.o[key] < other.o[key]: return asc
        if self.o[key] > other.o[key]: return not asc
  return K

orders = [
  {'id': 1, 'name': 'Ashley', 'date': '2020-05-20'},
  {'id': 2, 'name': 'Peter' , 'date': '2020-05-20'},
  {'id': 3, 'name': 'Ashley', 'date': '2020-05-05'},
  {'id': 4, 'name': 'John'  , 'date': '2020-05-05'},
  {'id': 5, 'name': 'Peter' , 'date': '2020-05-05'},
]

# 원본
pprint( orders )
# name 오름차순
pprint( sorted(orders, key=orderBy(['name'])) )
# name 내림차순
pprint( sorted(orders, key=orderBy(['name'],ascending=[False])) )
# name, id 오름차순
pprint( sorted(orders, key=orderBy(['name','id'])) )
# name 오름차순, id 내림차순
pprint( sorted(orders, key=orderBy(['name','id'],ascending=[True,False])) )
# name, id 내림차순
pprint( sorted(orders, key=orderBy(['name','id'],ascending=[False,False])) )
# name 내림차순, id 오름차순
pprint( sorted(orders, key=orderBy(['name','id'],ascending=[False,True])) )

2 같이 보기[ | ]

문서 댓글 ({{ doc_comments.length }})
{{ comment.name }} {{ comment.created | snstime }}