Python I';我理解这个代码有困难
我是python新手,试图通过在hackerrank上练习来学习。我不理解这个列表概念。这就是问题所在 输入格式: 第一行包含一个整数,即学生人数。 后面的几行描述了每一个学生;第一行包含学生的姓名,第二行包含他们的成绩 约束 总会有一个或多个学生的成绩是第二低的 输出格式: 打印物理成绩第二低的任何学生的姓名;如果有多个学生,按字母顺序排列他们的名字,并将每个名字打印在新行上 样本输入0:Python I';我理解这个代码有困难,python,nested-lists,Python,Nested Lists,我是python新手,试图通过在hackerrank上练习来学习。我不理解这个列表概念。这就是问题所在 输入格式: 第一行包含一个整数,即学生人数。 后面的几行描述了每一个学生;第一行包含学生的姓名,第二行包含他们的成绩 约束 总会有一个或多个学生的成绩是第二低的 输出格式: 打印物理成绩第二低的任何学生的姓名;如果有多个学生,按字母顺序排列他们的名字,并将每个名字打印在新行上 样本输入0: 5 骚扰 37.21 浆果 37.21 蒂娜 37.2 阿克里蒂 41 严厉的 39 样本输出0: B
5
骚扰
37.21
浆果
37.21
蒂娜
37.2
阿克里蒂
41
严厉的
39
样本输出0:
Berry
骚扰
代码
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\u列表是否为空?为了更好地理解,我在代码中添加了注释,希望这有帮助
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")
这是python2还是python3?@DeveshKumarSingh它的python3,看看印刷品function@WimanicesirPython2(原始输入
)。print函数来自导入。在列表中使用元组,然后按分数排序,这不是更好吗?另外,score\u list[score].append(name)
,这有什么作用?附加字符串?@dustin我们的score\u list[score]
类型为'list',score\u list[score]。附加(名称)
将附加到该列表。