简体   繁体   English

返回.txt文件内容

[英]Returning .txt file contents

I have a file, Testing.txt : 我有一个文件, 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: 我正在尝试创建一个获取此文件并返回的函数:

  • The average of all the grades (last numbers in the file of each line), 所有等级的平均值(每行文件中的最后一个数字),
  • and the ID (long numbers within file) of the highest and lowest grades. 和最高和最低等级的ID(文件中的长数)。

I know how to get the average but am stuck trying to get the IDs. 我知道如何获得平均值,但我很难尝试获取ID。

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)

You can use a list comprehension to get the desire pairs of ID and score : 您可以使用列表理解来获得所需的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']]

Then for calculation the average you can use zip within map and sum functions: 然后计算平均值,你可以在mapsum函数中使用zip

>>> 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 : 对于minmax使用内置函数 minmax使用正确的键:

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'

I think using the python csv module would help. 我认为使用python csv模块会有所帮助。 Here is several examples : http://nbviewer.ipython.org/github/rasbt/python_reference/blob/master/tutorials/sorting_csvs.ipynb 以下是几个例子: http//nbviewer.ipython.org/github/rasbt/python_reference/blob/master/tutorials/sorting_csvs.ipynb

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM