[파이썬] - 정렬 함수 ( sort, sorted 와 reverse, key )

zsunny·2022년 7월 11일
0

[Python] 문법

목록 보기
15/18

🔎 sort( )

nums = [3, 2, 5, 1, 4]
nums.sort()
print(nums)			# [1, 2, 3, 4, 5]

🔎 sorted( )

nums = [3, 2, 5, 1, 4]
print(sorted(nums))			# [1, 2, 3, 4, 5]

🔎 파라미터 - reverse, key

1️⃣ reverse

  • reverse에는 bool값을 넣는다. (default는 False(오름차순))
# sort() 사용
nums = [3, 2, 5, 1, 4]
nums.sort(reverse=True)
print(nums)			# [5, 4, 3, 2, 1]

# sorted() 사용
nums = [3, 2, 5, 1, 4]
print(sorted(nums), reverse=True)			# [5, 4, 3, 2, 1]

2️⃣ key

  • key에는 정렬을 목적으로 하는 함수를 값으로 넣는다. (default는 오름차순)

☝️ len 함수 이용

# sort() 사용
strs = ['coding', 'hello', 'new_world']
strs.sort(key=len)
print(strs)						# ['hello', 'coding', 'new_world']

# sorted() 사용
strs = ['coding', 'hello', 'new_world']
print(sorted(strs, key=len))	# ['hello', 'coding', 'new_world']

✌️ 람다 함수 이용

# sort() 사용
strs = ['coding', 'hello', 'new_world']
strs.sort(key=lambda x: x[1])
print(strs)									# ['hello', 'new_world', 'coding']

# sorted() 사용
strs = ['coding', 'hello', 'new_world']
print(sorted(strs, key=lambda x: x[1]))		# ['hello', 'new_world', 'coding']

🪄 여러요소를 갖는 경우

  • [0]인덱스로 오름차순 정렬하고 같은 값인경우 [1]인덱스로 내림차순 정렬
nums = [(3, 15), (3, 11), (2, 13), (5, 10), (2, 12)]
nums.sort(key=lambda x: (x[0], -x[1]))		# '-' 로 내림차순
print(nums)					# [(2, 13), (2, 12), (3, 15), (3, 11), (5, 10)]

🙏 참고

👉 파이썬 정렬 함수 sort, sorted_key = lambda, function / reverse=파라미처 이용 방법 (Python)

⭐️ 활용 문제

👉 [백준 5635 파이썬] - 생일

profile
매일 성장하는 예비 웹 개발자 🌱

0개의 댓글