Reputation: 27
I'm reading from a .txt file and have four scores for each person, i need to find out how to take the scores from each line and find the average for each person.
s={}
results= open("surf.txt")
for line in results:
(s['Name'], s['scoreOne'], s['scoreTwo'], s['scoreThree'], s['scoreFour']) =line.split(";")
That seems like all the code that's needed to figure this out.
surf.txt contains:
Johnny;8.65;7.32;7.81;9.12
Juan;9.12;8.45;8.80;5.60
Joseph;8.45;9.00;9.12;9.13
Stacey;7.81;8.33;9.00;8.10
(...)
Upvotes: 0
Views: 1715
Reputation: 27575
file cici.csv
Johnny;8.65; 7.32;7.81;9.12
Juan;9.12;8.45;8.80;5.60 ; 12.455 ; 2
Joseph Maria y Borbon;8.45;9.00;9.12;9.13
Stacey ;7.81 ;8.10
code
import csv
rid = csv.reader(open('cici.csv','rb'),delimiter=(';'))
av = dict( (row[0].strip(),sum(map(float,row[1:]))/(len(row)-1)) for row in rid)
print av
result
{'Joseph Maria y Borbon': 8.925, 'Juan': 7.7375, 'Stacey': 7.955, 'Johnny': 8.225}
Upvotes: 0
Reputation: 12084
Solution:
separator = ";"
inputFile = "input.txt"
with open(inputFile) as f:
for line in f:
values = line.split(separator)
name = values[0]
scores = map(float, values[1:])
avg = sum(scores) / len(scores)
print name, avg
Input:
Maciej;5;10;15;50
John;15;8;10;14
Mike;5;5;5;5
Output:
Maciej 20.0
John 11.75
Mike 5.0
Upvotes: 2
Reputation: 22690
You can slice the result list with [1:]
for line in results:
scores = line.split(';')[1:]
scores = map(float, scores) # Conversion to float
average = sum(scores)/len(scores)
that's also more general, because you won't depend on number of scores, just reject the first element :)
Upvotes: 1
Reputation: 42072
If your file has the following format:
john; 1; 2; 3; 4
pete; 5; 4; 3; 2
joan; 9; 8; 7; 6
Then you can simply:
with open('surf.txt', 'rb') as fp:
for line in fp.readlines():
tokens = line.strip().split(';') # this creates a list of strings
name = tokens[0] # extract the first (left-most) string (the name)
nums = [float(k) for k in tokens[1:]] # convert strings to floats
mean = sum(nums) / len(nums) # compute the arithmetic mean
print "%s has a mean of %f" % (name, mean) # print the result
Notice that this example would NOT work if the person had more than one name: it assumes that there is only ONE column for the name, and the remaining columns can be converted to floats.
Upvotes: 1