Reputation: 37
I have a file, Testing.txt
:
type,stan,820000000,92
paul,tanner,820000095,54
remmy,gono,820000046,68
bono,Jose,820000023,73
simple,rem,820000037,71
I'm trying to create a function that takes this file and returns:
I know how to get the average but am stuck trying to get the IDs.
So far my code looks like this:
#Function:
def avg_file(filename):
with open(filename, 'r') as f:
data = [int(line.split()[2]) for line in f]
return sum(data)/len(data)
avg = avg_file(filename)
return avg
#main program:
import q3_function
filename = "testing.txt"
average = q3_function.avg_file(filename)
print (average)
Upvotes: 1
Views: 82
Reputation: 107287
You can use a list comprehension to get the desire pairs of ID and score :
>>>l= [i.split(',')[-2:] for i in open(filename, 'r') if not i=='\n']
[['820000000', '92'], ['820000095', '54'], ['820000046', '68'], ['820000023', '73'], ['820000037', '71']]
Then for calculation the average you can use zip
within map
and sum
functions:
>>> avg=sum(map(int,zip(*l)[1]))/len(l)
>>> avg
71
And for min
and max
use built-in functions min
and max
with a proper key :
max_id=max(l,key=itemgetter(1))[0]
min_id=min(l,key=itemgetter(1))[0]
Demo :
>>> from operator import itemgetter
>>> max(l,key=itemgetter(1))
['820000000', '92']
>>> max(l,key=itemgetter(1))[0]
'820000000'
>>> min(l,key=itemgetter(1))[0]
'820000095'
>>> min(l,key=itemgetter(1))
['820000095', '54']
>>> min(l,key=itemgetter(1))[0]
'820000095'
Upvotes: 2
Reputation: 3157
I think using the python csv
module would help.
Here is several examples : http://nbviewer.ipython.org/github/rasbt/python_reference/blob/master/tutorials/sorting_csvs.ipynb
Upvotes: 1