【问题标题】:Read the Elements of an List one-by-one in Python3在 Python3 中逐一读取列表的元素
【发布时间】:2016-12-19 09:18:52
【问题描述】:

我正在编写一个程序来查找排序列表在每次传递中的排名。 我的程序在这里:

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

但我得到了其他错误的答案。 (我只需要唯一分数的排名) 应该怎么做?

【问题讨论】:

  • 你确定你的输出吗?恕我直言,如果两个学生得 100 分,而 Alice 得 50 分,她应该是第三名,所以我预计 8 6 3 1。如果你想对独特的分数进行排名,你应该说出来。

标签: python arrays list python-3.x


【解决方案1】:

您的代码的根本原因是因为extend 在循环中,每个循环的结果都取决于其他循环。 extend 在每个循环中添加 ALL 的 Alice 分数。

  1. 原始分数:[100, 100, 50, 40, 40, 20, 10]
  2. 第一个循环:[120, 100, 100, 50, 50, 40, 40, 25, 20, 10, 5]
  3. 第二个循环:[120, 120, 100, 100, 50, 50, 50, 40, 40, 25, 25, 20, 10, 5, 5]

代替extend(alice),使用append(i) 可以解决您的问题。因为append 在每个循环中只添加 ONE 个 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]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-02-17
    • 2011-08-09
    • 2014-03-05
    • 1970-01-01
    • 2019-01-19
    • 2019-01-12
    • 2021-01-09
    相关资源
    最近更新 更多