如何从成绩表中找到亚军的成绩?

问题描述 投票:0回答:4

根据您大学运动会的参赛者成绩表,您需要找到亚军的成绩。给你 n 个分数。将它们存储在列表中并找到亚军的分数。

我尝试在列表中排列n个分数,以便我可以从列表中选择亚军的分数。我只期望亚军的分数,但得到了整个列表作为输出。

python arrays list arraylist list-comprehension
4个回答
0
投票

获得亚军分数的一些步骤:

  1. 使用
    sorted()
    函数对分数列表进行升序排序
  2. 列表排序后,使用
    pop()
    函数从列表中删除最高分
  3. 再次使用
    pop()
    从列表中删除新的最后一个元素并将其存储到新变量中。新变量作为亚军的得分出现。
  4. 打印亚军成绩

示例代码:

# Create a list of scores
scores = [100, 95, 85, 75, 65]

# Sort the list of scores in ascending order
scores = sorted(scores)

# Remove the last element (the highest score) from the list
scores.pop()

# Remove the new last element (the runner-up score) from the list
runner_up_score = scores.pop()

# Print the runner-up score
print(runner_up_score)

0
投票

首先对列表进行降序排序,然后选择列表中的第二项?列表[1]

您在排序列表或打印列表时遇到问题吗?

list=[3,0,1,2]
list.sort(reverse=True)
print(list[1])

0
投票

注意:- 假设相同分数的排名相同

代码:-

#Method 1
#Using remove and find max element
arr = map(int, input("Enter the scores of the students:\n").split())
arr=set(arr)
if arr:
    arr.remove(max(arr))
if arr:
    print(max(arr))
else:
    print("There is no runner up")
#Method2
#Using sort concept with set and list
arr = map(int, input("Enter the scores of the students:\n").split())
arr=list(set(arr))
arr.sort()
if len(arr)>1:
    print(arr[-2])
else:
    print("There is no runner up")

输出:-

测试用例1:当两个人拥有最高分数时[即有两个第一名]

Enter the scores of the students:
89 76 43 68 67 89
76

测试用例2:所有分数都不同

Enter the scores of the students:
76 89 99 56
89

测试用例3:分数都是相等的。

Enter the scores of the students:
85 85 85 85 
There is no runner up

Testcase4 用户仅输入一个分数。

Enter the scores of the students:
56
There is no runner up

Testcase5 用户未输入任何分数。

Enter the scores of the students:

There is no runner up

0
投票
  1. 您可以使用两个变量,
    top
    prev
    ,并且当
    top
    值更改为更高的值,将其先前的值存储在
    prev
    中。 这样,你就能获得第二高了。
  2. 您可以使用
    sorted()
    .sort()
    对列表进行排序并使用
    pop()
    然后得到
    listname[-1]
    值。
© www.soinside.com 2019 - 2024. All rights reserved.