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

(새 문서: 분류: 정렬 ==개요== ;orderBy() ==PHP== 분류: PHP {{참고|PHP orderBy()}} ==Python== 분류: Python {{참고|파이썬 orderBy()}} <source lang='python'> from pp...)
 
 
(사용자 2명의 중간 판 7개는 보이지 않습니다)
10번째 줄: 10번째 줄:
[[분류: Python]]
[[분류: Python]]
{{참고|파이썬 orderBy()}}
{{참고|파이썬 orderBy()}}
<source lang='python'>
<syntaxhighlight lang='python' run>
from pprint import pprint  
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 = [
employees = [
{'EmployeeID':'1', 'Name':'한놈',  'BirthDate':'1999-01-01'},
{'EmployeeID':'1', 'Name':'한놈',  'BirthDate':'1999-01-01'},
18번째 줄: 29번째 줄:
{'EmployeeID':'4', 'Name':'너구리', 'BirthDate':'2000-01-01'}
{'EmployeeID':'4', 'Name':'너구리', 'BirthDate':'2000-01-01'}
]
]
 
pprint( sorted(employees, key=orderBy(['BirthDate'])) )
employees.sort(key=lambda x: x['Name'])
pprint( sorted(employees, key=orderBy(['BirthDate','Name'],ascending=[False,True])) )
employees.sort(key=lambda x: x['BirthDate'], reverse=True)
</syntaxhighlight>
 
pprint( employees )
#[{'BirthDate': '2000-01-01', 'EmployeeID': '4', 'Name': '너구리'},
# {'BirthDate': '2000-01-01', 'EmployeeID': '2', 'Name': '두시기'},
# {'BirthDate': '1999-01-01', 'EmployeeID': '3', 'Name': '석삼'},
# {'BirthDate': '1999-01-01', 'EmployeeID': '1', 'Name': '한놈'}]
</source>

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 }}