繁体   English   中英

我在理解此代码时遇到麻烦

[英]I'm having trouble understanding this code

我是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空的?

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

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")

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

# 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")

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM