简体   繁体   English

Python:如何在使用for循环和文件时订购列表。 (家庭作业)

[英]Python: How to order a list while using for loops and a file. (Homework)

Basically I need the names of the students to be attributed to their respective grades in the order of the list. 基本上,我需要按照列表的顺序将学生的姓名归入各自的年级。 So this is what I have so far: 所以这就是我到目前为止:

def main():

Define myFile and open/read grades.txt file 定义myFile并打开/读取grades.txt文件

myFile = open("grade.txt", "r")

Define the number of students and grade percentages for assignments, quizzes and exams 定义作业,测验和考试的学生人数和成绩百分比

numStudents = int(myFile.readline())
prctgs = myFile.readline().split()
students = ["Amy", "Jack", "Arron", "Zack", "Jen", "Jane"]

Create for loop to go through each of the students' scores 创建for循环以查看每个学生的分数

for i in range(numStudents):

Store each student's grades 储存每个学生的成绩

stdntGrades = myFile.readline().split()

Calculate grade percentage 计算成绩百分比

grade = 0
for j in range(len(prctgs)):
    grade = grade + float(prctgs[j]) * int(stdntGrades[j])
    print("Student #", i+1, ": ", " %.2f" % grade, sep="")

myFile.close()

main()

'students' is the list in question, I had also tried to directly input the names into the file but that failed miserably “学生”是有问题的列表,我也曾尝试将姓名直接输入文件中,但失败了

The 'grade.txt' file has the following in it: “ grade.txt”文件中包含以下内容:

6
.3 .1 .6
90 89 78
96 92 79
85 100 94
87 92 96
81 88 93
85 91 99

Note: This is my fifth program, so I am a complete beginner. 注意:这是我的第五个程序,所以我是一个完整的初学者。

The students' names should be part of the data, not the code: 学生姓名应该是数据的一部分,而不是代码:

6
.3 .1 .6
Amy 90 89 78
Jack 96 92 79
Aaron 85 100 94
Zack 87 92 96
Jen 81 88 93
Jane 85 91 99

Then read them in along with the data: 然后将它们与数据一起读入:

line = file.readline().split()
student = line[0]
prctgs = line[1:]

Lets assume we have 2 strings ... 假设我们有2个字符串...

weights = "0.3 0.1 0.3"
grades =  "90   87  92"

You already know that you can split these up into lists: 您已经知道可以将它们分成几个列表:

weights.split() #['0.3', '0.1', '0.3]
grades.split() #['90', '87', '92']

Now you say to yourself -- "Wouldn't it be nice if I could get the matching numbers at the same time?" 现在您对自己说:“如果我能同时获得匹配的号码,那会很好吗?” Well, you can. 好吧,可以。 That's what zip is built for: 这就是zip目的:

total = 0
for weight,grade in zip(weights.split(),grades.split()):
    total += float(weight)*float(grade)

This can even be shortened using sum if you'd like: 如果您愿意,甚至可以使用sum来缩短:

total = sum( float(w)*float(g) for w,g in zip(weights.split(),grades.split() )

So, this gives you one person's total. 因此,这给您一个人的总数。 Now, we can use the same concept when working with the file. 现在,在处理文件时,我们可以使用相同的概念。 We want to "zip" the person's name with their grade information. 我们想用他们的成绩信息“压缩”该人的名字。 Here's how: 这是如何做:

with open('grade.txt') as data: #fancy way of opening files...
    npeople = int(next(data)) #read first line, make an integer
    weights = [float(x) for x in next(data).split()] #get the weights as a list of floats
    people = ['jack','jill','mary','little miss muffet','kermit','animal']
    for person, grade_info in zip(people,data):
        grade = sum( w*float(g) for w,g in zip(weights,grade_info.split() )
        print person,grade

Another trick that I've used here is next(fileobject) . 我在这里使用的另一个技巧是next(fileobject) That's just a fancy way of saying fileobject.readline() . 那只是说fileobject.readline()一种奇特的方式。 In fact, in python3.x, fileobject.readline() no longer exists ... Might as well get used to using next now :). 实际上,在python3.x中, fileobject.readline()不再存在……现在也可能习惯于使用next :)。

The 4 builtin functions that I've used here are zip , next , float and sum . 我在这里使用的4个内置函数zipnextfloatsum float and sum are pretty obvious how they work so they don't take much work to explain. floatsum很明显是如何工作的,因此不需要太多工作来解释。 zip and next are a little more tricky. zipnext更棘手。 Read the linked docs until you understand them. 阅读链接的文档,直到您理解它们为止。 They're super useful. 它们超级有用。 I've also used list-comprehensions for building some lists. 我还使用列表理解来构建一些列表。 They're super useful as well. 它们也非常有用。 Definitely something you want in your python utility belt. 绝对是您在python实用程序皮带中想要的东西。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM