I have a file with 3 scores for each person. I want to use these scores, and get the average of all 3 of them. There scores are separated by tabs and in descending order. For example:
jack 10 6 11
claire 3 7 3
conrad 5 4 6
these people would come out with an average of:
jack 9
conrad 5
claire 4
I want these to be able to print to the python shell, however not be saved to the file.
with open("file.txt") as file1:
d = {}
for line in file1:
column = line.split("/t")
names = column[0]
scores = int(column[1].strip())
I have made a start, but I have found myself stuck and I do not know how to continue with the coding. Does anyone have a solution?
答案 0 :(得分:0)
Use the concept of a set, or a dictionary. Both are similar: they can only contain a certain "key" once.
So if you created a dictionary that stored the contents of each score, using the 'name' as a key, you could create a data structure that looked something like this:
student_scores = {'dave': [9, 8, 11], 'john': [12, 7, 10], ... }
That data structure would be something you could analyze in a second step, easily enough, to calculate averages.
Then write a loop that goes through your student_scores
, and averages each one. You can loop through a dictionary like this:
for name, list_of_scores in student_scores.items():
# do something with name & list...
Hope that gives you some ideas, without just coding it for you!
Also: Remember of course that "average" is defined as the sum
of a list of numbers, divided by the len
of a list of numbers. Lucky for you, both of these built-in functions exist in Python, and operate on lists!
答案 1 :(得分:0)
You could use a dictionary.
scores = {}
with open("class6Afile.txt") as file1:
for line in file1:
column = line.split("/t")
names[column[0]] = column[1:]
Post this, you can iterate over key,value pairs as shown here and find the average over each set of value against the corresponding name.
Also , you can't store names in an array the way you have done it. I'm assuming names is an array, so the correct way to do it is.
names.append(column[0])
答案 2 :(得分:0)
with open("class6Afile.txt") as file1:
d = {}
class Person:
def __init__(self, name, average):
self.name = name
self.average = average
for line in file1:
column = line.split("/t")
name = column[0]
average = (int(column[1].strip()) + int(column[2].strip()) + int(column[3].strip()))/3
d.append(Person(name,average))
d.sort(key=lambda x: x.average, reverse=True)
您想要的结果存在于列表顶部!