我有一个文件Testing.txt
:
type,stan,820000000,92
paul,tanner,820000095,54
remmy,gono,820000046,68
bono,Jose,820000023,73
simple,rem,820000037,71
我试图创建一个获取此文件并返回的函数:
我知道如何获得平均值,但我很难尝试获取ID。
到目前为止,我的代码看起来像这样:
#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)
答案 0 :(得分:2)
您可以使用列表推导来获得所需的ID和分数对:
>>>l= [i.split(',')[-2:] for i in open(filename, 'r') if not i=='\n']
[['820000000', '92'], ['820000095', '54'], ['820000046', '68'], ['820000023', '73'], ['820000037', '71']]
然后,为了计算平均值,您可以在zip
和map
函数中使用sum
:
>>> avg=sum(map(int,zip(*l)[1]))/len(l)
>>> avg
71
min
和max
使用built-in functions min
和max
并使用正确的密钥:
max_id=max(l,key=itemgetter(1))[0]
min_id=min(l,key=itemgetter(1))[0]
演示:
>>> 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'
答案 1 :(得分:1)
我认为使用python csv
模块会有所帮助。
以下是几个示例:http://nbviewer.ipython.org/github/rasbt/python_reference/blob/master/tutorials/sorting_csvs.ipynb