Python CSV作业程序

2024-10-16 20:45:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个家庭作业要做,必须通过csv和函数读取文件。在

其基本思想是计算足球运动员在两年内的冲刺得分。我们使用给我们的文件中的数据。示例文件为:

name, ,pos,team,g,rush,ryds,rtd,rtdr,ravg,fum,fuml,fpts,year 
A.J.,Feeley,QB,STL,5,3,4,0,0,1.3,3,2,20.3,2011
Aaron,Brown,RB,DET,1,1,0,0,0,0,0,0,0.9,2011
Aaron,Rodgers,QB,GB,15,60,257,3,5,4.3,4,0,403.4,2011
Adrian,Peterson,RB,MIN,12,208,970,12,5.8,4.7,1,0,188.9,2011
Ahmad,Bradshaw,RB,NYG,12,171,659,9,5.3,3.9,1,1,156.6,2011

换句话说,我们必须从文件中去掉第一行,然后读取其余的行,用逗号分隔。在

要计算rusher额定值,我们需要:

Yds is the average yards gain per attempt. This is [total yards / (4.05 * attempts)]. If this number is greater than 2.375, then 2.375 should be used instead.

perTDs is the percentage of touchdowns per carry. This is [(39.5 * touchdowns) / attempts]. If this number is greater than 2.375, then 2.375 should de used insted.

perFumbles is the percentage of fumbles per carry. This is [2.375 - ((21.5 * fumbles) / attempts)].

The rusher rating is [Yds + perTDs + perFumbles] * (100 / 4.5).

到目前为止我掌握的代码是:

^{pr2}$

所以是的,还有很多函数需要我定义。但到目前为止,你对代码有什么看法?效率低下吗?你能告诉我它怎么了吗?因为在我看来这段代码会非常长(比如300行左右),但是老师说这应该是一个相对较短的项目。在


Tags: 文件the函数代码ifisthisaaron
1条回答
网友
1楼 · 发布于 2024-10-16 20:45:16

这里有一段代码可以大大简化整个项目。在

理解手头的任务可能需要一点时间,但总的来说,当您处理正确的数据类型和“关联数组”(dicts)时,这将使您的生活更加轻松

import csv

reader = csv.DictReader(open('mycsv.txt', 'r'))
#opens the csv file into a dictionary

list_of_players = map(dict, reader)
#puts all the dictionaries (by row) as a separate element in a list. 
#this way, its not a one-time iterator and all your info is easily accessible

for i in list_of_players:
    for stat in ['rush','ryds','rtd','fum','fuml','year']:
        i[stat] = int(i[stat])
    #the above loop makes all the intended integers..integers instead of strings
    for stat in ['fpts','ravg','rtdr']:
        i[stat] = float(i[stat])
    #the above loop makes all the intended floats..floats instead of strings

for i in list_of_players:
    print i['name'], i[' '], i['fpts']
    #now you can easily access and loop through your players with meaningful names
    #using 'fpts' rather than predetermined numbers [5]

此示例代码显示了如何轻松地处理他们的姓名及其统计信息,即firstname、lastname和fpts:

^{pr2}$

当然,为了获得所有请求的统计信息(max等),需要进行一些调优,但是这样做可以从一开始就保持数据类型的正确性,从而减少执行这些任务的繁琐程度。在

现在(使用这些构造)可以在不到300行的时间内完成这个任务,而且使用python越多,您将学习完成这些任务的传统习惯用法。lambda和sorted()是您将爱上的函数的例子…时间!在

相关问题 更多 >