10814번 나이순 정렬
풀이 방법
- 입력을 age와 name으로 나누어 (age, name)인 튜플을 배열에 추가한다
- 정렬할 때 key속성을 통해 age를 기준으로 정렬한다
- 파이썬 내장 정렬은 stable(배열에 먼저 담긴 순서대로 정렬)
풀이
Python
n = int(input())
members = list()
for _ in range(n):
age, name = input().split(" ")
members.append((int(age), name))
sorted_members = sorted(members, key=lambda x: x[0])
for member in sorted_members:
print(member[0], member[1])
Swift
let n = Int(readLine()!)!
var members: [(Int, Int, String)] = []
for count in 1...n {
let ageAndName = readLine()!.split(separator: " ")
let age = Int(ageAndName[0])!
let name = String(ageAndName[1])
members.append((count, age, name))
}
let sortedMembers = members.sorted {
if $0.1 == $1.1 {
return $0.0 < $1.0
}
return $0.1 < $1.1
}
for member in sortedMembers {
print(member.1, member.2)
}