简体   繁体   English

将一个列表中的字符串与另一个列表中的整数“配对”的最简单方法是什么(在python中)?

[英]What is the easiest way “pair” strings in one list with integers in another (in python)?

I'm working on a school project which has to store the names of people and their respective score on a test in a list so that I can manipulate it to find averages as well as printing out each persons score with their name. 我正在做一个学校项目,该项目必须将人的姓名和他们各自的分数存储在列表中的测试中,以便我可以操纵它来查找平均值,并打印出每个人的分数及其姓名。 Relatively new to Python so any help is appreciated :) 对Python来说相对较新,因此可以提供任何帮助:)

I would recommend using a dictionary. 我建议使用字典。 This pairs keys (the name of students) to values (the score on a test). 这会将键(学生的姓名)与值(测验的分数)配对。 Here is an example below that gets you the output that you would want. 下面是一个示例,可为您提供所需的输出。

import math

student_scores = {}

student_scores['Rick'] = 89
student_scores['Pat'] = 79
student_scores['Larry'] = 82
score_list = []

for name, score in student_scores.items():
         score_list.append(score)
         print(name.title() + "'s score was: " + str(score) + '%')

sum_scores = sum(score_list)
division_scores = len(score_list)
average_score = sum_scores / division_scores
print('The average score was {0:.2f}%'.format(average_score))
  1. I created an empty dictionary that you will use to add student names and scores to a list. 我创建了一个空字典,您将使用该字典将学生姓名和分数添加到列表中。 So in the dictionary (student_scores) The student name 'Rick' will be a key, and the score 89 will the value. 因此,在字典(student_scores)中,学生名“ Rick”将是一个键,分数89将是该值。 I do this for 2 additional students, pairing their name up with the score that they received. 我为另外2名学生做这件事,将他们的名字与他们获得的分数配对。

  2. I create an empty list called score_list. 我创建一个名为score_list的空列表。 You'll use this list later to add he sum of all scores, and divide by the number of total scores to get an average score for your test. 稍后,您将使用此列表将所有分数的总和相加,然后除以总分数的数量即可得出测试的平均分数。

  3. We start a for loop that iterates over each key and value in your dictionary. 我们开始一个for循环,该循环遍历字典中的每个键和值。 For each score, we append it to the empty score list. 对于每个分数,我们将其附加到空白分数列表中。 For each name and score, we print a message showing what the student got on the test. 对于每个姓名和分数,我们会打印一条消息,显示学生在考试中得到了什么。

  4. Now that we have appended the scores to the dictionary we can use the sum method to get the sum of all scores in your score list. 现在,我们已将分数添加到字典中,我们可以使用sum方法来获取分数列表中所有分数的总和。 We put it in a variable called sum_scores. 我们将其放在一个名为sum_scores的变量中。 We also get the number of scores in your list by finding the length of the list (which will be 3 in this case since I put 3 scores in it). 我们还通过找到列表的长度来获得列表中分数的数量(在本例中为3,因为我在其中输入了3个分数)。 We will store that in a variable called division_scores (since I am dividing the sum of all scores by the number of scores recorded). 我们会将其存储在一个名为division_scores的变量中(因为我将所有分数的总和除以记录的分数数)。 We create a variable called average_score which is the result of the sum of scores divided by the total number of observations. 我们创建一个称为average_score的变量,该变量是分数总和除以观察总数的结果。

  5. We then print what the average score was using the .format() method. 然后,我们使用.format()方法打印平均得分。 We just format the average score so that you get it to extend two decimal places {0:.2f}%. 我们只是格式化平均分数,以便您将其扩展到小数点后两位{0:.2f}%。

Your output is as follows: 您的输出如下:

Rick's score was: 89%
Pat's score was: 79%
Larry's score was: 82%
The average score was 83.33%

The above answer is a great data structure for pairing strings. 上面的答案是用于配对字符串的很好的数据结构。 It'll set you on the right track for enumerating scores, averages, etc in simple cases. 在简单的情况下,它将使您走上正确的道路,以枚举分数,平均值等。

Another way to store relationships is with classes (or tuples, at the bottom!) There's a rough sketch of an OOP approach below. 存储关系的另一种方法是使用类(或底部的元组!)。下面是OOP方法的粗略概图。

The most important parts are 最重要的部分是

  1. The properties of the ExamAttempt class store the information (names, scores) ExamAttempt类的属性存储信息(名称,分数)

  2. In the Exam.record_attempt method, a new ExamAttempt object is created from the ExamAttempt class and added to the list of attempts on the Exam object. Exam.record_attempt方法中,从ExamAttempt类创建一个新的ExamAttempt对象,并将其添加到Exam对象的attempts列表中。

From here, you could easily add other features. 从这里,您可以轻松添加其他功能。 You'd probably want to model a Question and Answer , and maybe a Student object too, if you're going all out. 如果您全力以赴,则可能要对Question and Answer建模,也可能对Student对象建模。 If you store questions and answers, as well as which answer each student selected, you can start doing things like throwing out questions, grading on a curve, discovering questions to throw out, etc. The OOP approach makes it easier to extend functionality like plotting all kinds of fancy graphs, export to CSV or Excel, and so on. 如果您存储问题和答案以及每个学生选择的答案,则可以开始进行诸如抛出问题,对曲线评分,发现要抛出的问题等操作。OOP方法使扩展诸如绘图之类的功能变得更加容易各种奇特的图形,导出为CSV或Excel等。

Not all of the code below is necessary.. it can definitely be simplified a little, or reimagined entirely, but hopefully this should give you enough to start looking down that path. 并非下面的所有代码都是必需的..可以将其完全简化或完全重新构想,但是希望这可以使您有足够的机会开始寻找这条路。 Even if it seems complicated now, it's not that bad, and it's what you'll want to be doing eventually (with Python, anyway!) 即使现在看起来很复杂,也没有那么糟,这是您最终想要做的(无论如何使用Python!)

class ExamAttempt:
    def __init__(self, id, name, correct, total):
        self.id = id
        self.name = name
        self.correct = correct
        self.total = total
        self.score = (self.correct / float(self.total))

    def __repr__(self):
        return "<ExamAttempt: Id={}, Student={}, Score={}>".format(self.id, self.name, self.score)

class Exam:
    def __init__(self, name, questions):
        self.name = name
        self.attempts = []
        self.questions = questions
        self.num_questions = len(questions)

    def __str__(self):
        return "<Exam ({})>".format(self.name)

    def load(self, filename):
        pass

    def saveAttemptsToFile(self, filename):
        pass

    def record_attempt(self, student_name, num_correct):
        id = len(self.attempts) + 1
        self.attempts.append(
            ExamAttempt(id, student_name, num_correct, self.num_questions))

    def get_student_attempt(self, student_name):
        for att in self.attempts:
            if student_name == att.name:
                return att

    def get_average_score(self):
        return "homework" 

    def get_results_by_score(self):
        return sorted(self.attempts, key=lambda x: x.score, reverse=True)

    def get_attempts_by_name(self):
        return sorted(self.attempts, key=lambda x: x.name)

if __name__ == '__main__':
    questions = ['Question?' for i in range(100)] # Generate 100 "questions" = 100%
    exam = Exam('Programming 101', questions)
    data = [('Rick', 89), ('Pat', 79), ('Larry', 82)]

    for name, correct in data:
        exam.record_attempt(name, correct)

    for attempt in exam.get_results_by_score():
        print("{} scored {}".format(attempt.name, attempt.score))

暂无
暂无

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

相关问题 将十六进制字节字符串列表转换为十六进制整数列表的最简单方法是什么? - What's the easiest way to convert a list of hex byte strings to a list of hex integers? 用另一个列表中的字符串替换一个列表中的所有整数 - replacing all integers in one list, with strings in another 在Python中,在包含字符串和浮点数的列表中查找最小值的最简单方法是什么? - In Python, what is the easiest way to find the smallest value in a list which contains both strings and floats? 列表理解 - 将一个列表中的字符串转换为另一个列表中的整数 - List comprehension - converting strings in one list, to integers in another 如何在 Python 中将一个列表中的整数添加到另一个列表中 - How to add the integers in one list to another in Python 将字符串列表与 python 中的数字数组连接起来的最简单方法是什么 - What is the easiest way to concatenate string list with number array in python 在Python中,将包含关键字对的列表添加到字典的最简单方法是什么? - In Python, what is the easiest way to add a list consisting of keyword pairs to a dictionary? 在Python中搜索字典列表的最简单方法是什么? - What is the easiest way to search through a list of dicts in Python? 将字符串列表转换为整数 PYTHON - Converting list of strings to integers PYTHON python中包含整数和字符串的列表 - list containing integers and strings in python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM