我在理解此代码时遇到问题

时间:2019-06-07 07:05:03

标签: python nested-lists

我是python的新手,正在尝试通过hackerrank进行学习。我不了解此列表概念。这是问题

输入格式:

第一行包含一个整数,即学生人数。 接下来的几行用行来描述每个学生;第一行包含学生的姓名,第二行包含学生的成绩。

约束

总会有一个或多个学生的成绩第二低。

输出格式:

打印任何物理成绩最低的学生的姓名;如果有多个学生,请按字母顺序排列其姓名,然后将每个姓名打印在新行上。

示例输入0:

5

Harry
37.21
Berry
37.21
Tina
37.2
Akriti
41
Harsh
39

示例输出0:

Berry

Harry

代码

from __future__ import print_function
score_list = {}
for _ in range(input()):
    name = raw_input()
    score = float(raw_input())
    if score in score_list:
        score_list[score].append(name)
    else:
        score_list[score] = [name]
new_list = []
for i in score_list:
     new_list.append([i, score_list[i]])
new_list.sort()
result = new_list[1][1]
result.sort()
print (*result, sep = "\n")

我在这里无法理解“输入”功能,in是否不检查列表中的值,因此score_list是否为空?

2 个答案:

答案 0 :(得分:1)

我在代码中添加了注释,以更好地理解,希望对您有所帮助。

from __future__ import print_function
# Create an empty dict
score_list = {}
# Take a number input and run this loop that many times
for _ in range(input()):
    name = raw_input()
    score = float(raw_input())
    # if value of score is an existing key in dict, add name to the value of that key
    if score in score_list:
        score_list[score].append(name)
    else:
        # Else create a key with score value and initiate the value with a list
        score_list[score] = [name]
new_list = []
for i in score_list:
     new_list.append([i, score_list[i]])
new_list.sort()
result = new_list[1][1]
result.sort()
print (*result, sep = "\n")

答案 1 :(得分:0)

第一次字典是空的,但是第二次不是。我在每一行都添加了评论。

# Import
from __future__ import print_function
# Create a new dictionary to save the scores
score_list = {}
# For every input, do something
for _ in range(input()):
    # Grab the name of the current user
    name = raw_input()
    # Grab the score of the current
    score = float(raw_input())
    # If the score is already in the list,
    # append the name to that score
    if score in score_list:
        score_list[score].append(name)
    # Else add the new score and name to the list
    else:
        score_list[score] = [name]
# Create a new list
new_list = []
# Copy score list into the new list
for i in score_list:
     new_list.append([i, score_list[i]])
# Sort on score value
new_list.sort()
# Return the second highest score
result = new_list[1][1]
# Sort the names of the result
result.sort()
# Print it
print (*result, sep = "\n")