在Python3中逐个读取列表的元素
我正在编写一个程序来查找每个过程中排序列表的排名。 我的节目在这里:在Python3中逐个读取列表的元素,python,arrays,list,python-3.x,Python,Arrays,List,Python 3.x,我正在编写一个程序来查找每个过程中排序列表的排名。 我的节目在这里: import sys # No. of Students considered n = int(input().strip()) # Scores of n students scores = [int(scores_temp) for scores_temp in input().strip().split(' ')] # No. of scores considered for alice m = int(input
import sys
# No. of Students considered
n = int(input().strip())
# Scores of n students
scores = [int(scores_temp) for scores_temp in input().strip().split(' ')]
# No. of scores considered for alice
m = int(input().strip())
# Scores of Alice
alice = [int(alice_temp) for alice_temp in input().strip().split(' ')]
for i in alice:
#temp1 = sorted(alice, reverse = True)
temp = alice
print(temp)
scores.extend(temp)
temp2 = sorted(scores, reverse = True)
unique = []
[unique.append(item) for item in temp2 if item not in unique]
print(unique.index(i)+1)
我对Alice分数的输入是:
>>> 45 87 23
我的目标是先处理45,然后在打印排名后再处理87,依此类推,但问题是只有在处理45、87和23后,才会打印排名,这会导致错误答案
应该怎样做才能得到正确的答案。
此处给出了输入和输出示例:
>>> n = 7
>>> scores = [100, 100, 50, 40, 40, 20, 10]
>>> m = 4
>>> alice = [5, 25, 50, 120]
相同的分数被赋予相同的等级,以使最高分数获得第一等级。例100为第一级
正确的输出是:
6
4
2
1
但我得到了其他一些错误的答案。(我只需要唯一分数的排名)
应该怎么做?代码的根本原因是因为
扩展
在循环中,每个循环的结果取决于其他循环extend
addALL每个循环中Alice的分数
for i in alice:
scores.append(i)
temp2 = sorted(scores, reverse = True)
unique = []
[unique.append(item) for item in temp2 if item not in unique]
print(unique.index(i)+1)
> alice = [5, 25, 50, 120]
6 #temp2: [100, 100, 50, 40, 40, 20, 10, 5]
4 #temp2: [100, 100, 50, 40, 40, 25, 20, 10, 5]
2 #temp2: [100, 100, 50, 50, 40, 40, 25, 20, 10, 5]
1 #temp2: [120, 100, 100, 50, 50, 40, 40, 25, 20, 10, 5]
append(i)
可以解决您的问题,而不是extend(alice)
。因为append
只在每个循环中添加一个Alice分数
for i in alice:
scores.append(i)
temp2 = sorted(scores, reverse = True)
unique = []
[unique.append(item) for item in temp2 if item not in unique]
print(unique.index(i)+1)
> alice = [5, 25, 50, 120]
6 #temp2: [100, 100, 50, 40, 40, 20, 10, 5]
4 #temp2: [100, 100, 50, 40, 40, 25, 20, 10, 5]
2 #temp2: [100, 100, 50, 50, 40, 40, 25, 20, 10, 5]
1 #temp2: [120, 100, 100, 50, 50, 40, 40, 25, 20, 10, 5]
注意:由于每个循环都依赖于其他循环,不同的输入顺序将影响结果
> alice = [120, 50, 25, 5]
1 #temp2: [120, 100, 100, 50, 40, 40, 20, 10]
3 #temp2: [120, 100, 100, 50, 50, 40, 40, 20, 10]
5 #temp2: [120, 100, 100, 50, 50, 40, 40, 25, 20, 10]
8 #temp2: [120, 100, 100, 50, 50, 40, 40, 25, 20, 10, 5]
你确定你的产出吗?如果两个学生得了100分,爱丽丝得了50分,她应该是第三名,所以我预计是8631。如果你想排名唯一的分数,你应该说出来。