"함수 orderBy()"의 두 판 사이의 차이

 
12번째 줄: 12번째 줄:
<syntaxhighlight lang='python' run>
<syntaxhighlight lang='python' run>
from pprint import pprint  
from pprint import pprint  
def orderBy(by, ascending=[]):
def orderBy(by, ascending=[]):
    class K:
  class K:
        def __init__(self, obj, *args): self.obj = obj
    def __init__(self, o, *args): self.o = o
        def __lt__(self, other):
    def __lt__(self, other):
          (x, y) = (self.obj, other.obj)
      for i, key in enumerate(by):
          for i, key in enumerate(by):
        asc = ascending[i] if i < len(ascending) else True
            asc = ascending[i] if i < len(ascending) else True
        if self.o[key] < other.o[key]: return asc
            if x[key] < y[key]: return asc
        if self.o[key] > other.o[key]: return not asc
            if x[key] > y[key]: return not asc
  return K
          return False
 
    return K
employees = [
employees = [
{'EmployeeID':'1', 'Name':'한놈',  'BirthDate':'1999-01-01'},
{'EmployeeID':'1', 'Name':'한놈',  'BirthDate':'1999-01-01'},

2021년 10월 2일 (토) 17:00 기준 최신판

1 개요[ | ]

orderBy()

2 PHP[ | ]

3 Python[ | ]

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

employees = [
{'EmployeeID':'1', 'Name':'한놈',   'BirthDate':'1999-01-01'},
{'EmployeeID':'2', 'Name':'두시기', 'BirthDate':'2000-01-01'},
{'EmployeeID':'3', 'Name':'석삼',   'BirthDate':'1999-01-01'},
{'EmployeeID':'4', 'Name':'너구리', 'BirthDate':'2000-01-01'}
]
pprint( sorted(employees, key=orderBy(['BirthDate'])) )
pprint( sorted(employees, key=orderBy(['BirthDate','Name'],ascending=[False,True])) )
문서 댓글 ({{ doc_comments.length }})
{{ comment.name }} {{ comment.created | snstime }}