名称和分配标记的排序列表

2024-06-16 15:01:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试编写一个代码,允许我输入2N行,由名字和分数组成,并按字母顺序将它们与名字和每个相应的分数并排输出

输入的一个例子是

3
Betty
60
Cathy
50
Annie
40

其结果是:

Annie : 40
Betty : 60
Cathy : 50

这就是我到目前为止所做的:

N = int(input())
for i in range (2*N):
    m = input()
    marks_list = m.split()

我尝试了几种不同的方法来尝试对列表进行排序,但到目前为止没有任何效果


Tags: 代码inforinput顺序字母range名字
3条回答

这是一个按字母顺序递增姓名的示例,随机生成学生的姓名和分数

import string 
import random 

li = []
print("")
N = int(input("Enter The Number of Students in the class : "))
print("")
def getRandomList():

    for i in range (N):
        newName = ''.join(random.choices(string.ascii_uppercase,k=3))
        name=str(newName)
        mark = random.randint(0, 100) 
        li.append((name, mark))
        sortedbyname = sorted(li, key=lambda tp: tp[0])

    print("Print the names and their marks sorted by name alphabetically")
    print("")
    print('{:5s} {:15s}  ' .format('Name','Marks'))
    print("")
    for i in range(N):
        print(f"{sortedbyname[i][0]}     {sortedbyname[i][1]}")
    print("")
    

getRandomList()    

样本随机列表的输出如下所示

Enter The Number of Students in the class: 10

Print the names and their marks sorted by name alphabetically

Name  Marks

CFN     90
DIL     96
MIA     26
OIG     35
SNH     11
TBU     45
THW     3
VIR     26
XYS     62
YIU     9

在着手编写代码之前,您需要先尝试一下文件。我建议你在阅读我的答案之前这样做

首先,我们读N,我们假设学生的数量。对于其中的每一个,我们将获取两个输入:名称和标记。因此,您只能运行一个循环N次,而不是2*N次,并且在每次迭代中,您将获得两个输入

其次,列表和元组将对您有很大帮助,创建一个元组列表以供以后排序将大大减少工作。因此,我们将为每个学生创建一个元组(名称、标记),并将该元组插入列表中

第三,最后在得到输入后,我们只需要排序。python中有一个非常方便的函数,可以为您完成排序部分,但我确实建议如果您不知道如何从内部执行排序步骤,您可以自己执行排序步骤。我的意思是至少实现任何排序算法

以下是解决方案:

N = int(input())
# list
li = []
for i in range (N):
   # taking two inputs
   name = input()
   mark = input()
   # creating a tuple and appending to list
   li.append((name, mark))

# sorting by name, the first element in the tuple, 
# that's why there is tp[0]
sortedbyname = sorted(li, key=lambda tp: tp[0])

# printing results
for i in range(N):
   print(f"{sortedbyname[i][0]}: {sortedbyname[i][1]}")

希望这有帮助

所以我想出了另一种使用字典的方法,这就是我想出的代码

N = int(input())
markslist = {}

for i in range(N)
    name = input
    mark = int(input())

    markslist[name]=mark

for name, mark in sorted(markslist.items())
    print(name, ":", mark)

相关问题 更多 >