我正在尝试使用插入排序对学生列表进行排序,并根据每个学生的分数对其进行排名。学生的数据包括姓名、卷号、地址和分数。
在这里,我将学生的Mark存储在一个列表Marklist
中,将学生的其他数据存储在第二个列表stdData
中。
我使用插入排序对学生成绩表进行了排序。但现在我有两个单独的列表。如何合并并打印每个学生的分数排序列表?
import csv
stdData = [] # store RollNum,student name last name,address
Marklist = [] # store the final mark of each student
#generallist=[]
with open("studentlist.csv", "r") as f1:
recordReader = csv.DictReader(f1)
for row in recordReader:
#generallist.append(row)
row['Mark']=int(row['Mark'])
Marklist.append(row['Mark'])
stdData.append(row['RollNo'])
stdData.append(row['Name'])
stdData.append(row['LastName'])
stdData.append(row['Address'])
print(Marklist)
print(stdData)
for i in range(1, len(Marklist)):
key = Marklist[i]
j = i - 1
while j >= 0 and key < Marklist[j]:
Marklist[j + 1] = Marklist[j]
j -= 1
Marklist[j + 1] = key
print("Sorted List: ",Marklist)
谢谢。
您非常接近正确的解决方案。答案在于
- 将学生详细信息存储为列表列表。例如:
[ [student1 details], [student2 details], [student3 details] ]
- 使用CCD_ 5的索引对CCD_
以下是为解决上述问题而修改的代码:
import csv
stdData = [] # store RollNum,student name last name,address
Marklist = [] # store the final mark of each student
generallist=[]
with open("studentlist.csv", "r") as f1:
recordReader = csv.DictReader(f1)
for row in recordReader:
#generallist.append(row)
row['Mark']=int(row['Mark'])
Marklist.append(row['Mark'])
tmp_data = []
tmp_data.append(row['RollNo'])
tmp_data.append(row['Name'])
tmp_data.append(row['LastName'])
tmp_data.append(row['Address'])
stdData.append(tmp_data) # Storing student details as list of lists
print(Marklist)
print(stdData)
for i in range(1, len(Marklist)):
key = Marklist[i]
data = stdData[i] # Sort the elements in stdData using indices of MarkList
j = i - 1
while j >= 0 and key < Marklist[j]:
Marklist[j + 1] = Marklist[j]
stdData[j+1] = stdData[j]
j -= 1
Marklist[j + 1] = key
stdData[j+1] = data
print("Sorted List: ",Marklist)
for student_data in stdData:
print(student_data)
尽管上面的解决方案给出了正确的答案,但它使用了两个列表。
我们可以使用键对列表进行排序(不需要是实际的列表元素(。下面的代码实现了它,是一个更好的解决方案。
import csv
stdData = [] # store RollNum,student name last name,address
with open("studentlist.csv", "r") as f1:
recordReader = csv.DictReader(f1)
for row in recordReader:
tmp_data = []
tmp_data.append(row['RollNo'])
tmp_data.append(row['Name'])
tmp_data.append(int(row['Mark']))
tmp_data.append(row['LastName'])
tmp_data.append(row['Address'])
stdData.append(tmp_data) # Storing student details as list of lists
print(stdData)
for i in range(1, len(stdData)):
key = stdData[i][2] # here the key is the mark
data = stdData[i] # we will copy the data to correct index
j = i - 1
while j >= 0 and key < stdData[j][2]:
stdData[j+1] = stdData[j]
j -= 1
stdData[j+1] = data
print("Sorted List:")
for rollno, name, mark, lastname, address in stdData:
print(rollno, name, mark, lastname, address)
快乐的编码。