Nested Lists
if __name__ == '__main__':
students = []
scores = []
for _ in range(int(input())):
name = input()
score = float(input())
student = [name, score]
students.append(student)
scores.append(score)
second_lowest_grade = sorted(set(scores))[1]
name_list = sorted(student[0] for student in students if student[1] == second_lowest_grade)
print("\n".join(name_list))
해설
점수가 두번째로 높은 학생을 찾는 코드이다.
Nested List
students = []
scores = []
for _ in range(int(input())):
name = input()
score = float(input())
student = [name, score]
students.append(student)
scores.append(score)
리스트는 순서가 있는 오브젝트의 집합이다. 리스트는 리스트를 포함할 수 있고 이는 차원과 관련이 있다.
예를들면 [ ]는 1차원, [ [ ] ]는 2차원, [ [ [ ] ] ] 는 3차원 ... 등 이다.
다른 리스트를 포함하는 리스트를 네스티드(Nested)/중첩 리스트라고 한다.
위 예제처럼 students 리스트를 만들고 그 안에 for문과 append를 통해 student 리스트를 넣을 수 있다.
append
# 리스트명.append(값)
>>> stock = ['삼성전자', 'LG전자', 'SK하이닉스']
>>> stock.append(1, '현대차')
>>> stock
append() takes exactly one argument (2 given)
>>> stock.append('현대차')
>>> stock
['삼성전자', 'LG전자', 'SK하이닉스', '현대차']
append는 값을 리스트 마지막 위치에 삽입시킨다.
파이썬에서 언더바( _ )의 쓰임
>>> _ for in range(3):
... print('hello')
hello
hello
hello
_ for in range:에서 _는 반복자 값(iterable value)에 의미를 부여하지 않고, 반복되는 특정 횟수에만 집중하는 경우 사용한다. 예를 들어 위 코드에서는 반복자 _가 0 1 2 값을 반복하며 hello란 값을 3번 출력한다.
'Develop > hackerrank.com' 카테고리의 다른 글
HackerRank Python Solution / Lists (0) | 2022.01.10 |
---|---|
HackerRank Python Solution / Finding the percentage (0) | 2022.01.07 |
HackerRank Python Solution / Find the Runner-Up Score! (0) | 2022.01.01 |
HackerRank Python Solution / List Comprehensions (0) | 2022.01.01 |
HackerRank Python Solution / Print Function (0) | 2022.01.01 |