我正在比较花名册上的球员之间的棒球统计数据。我的数据是按行组织的,其中包含球员的姓名、击球率、比赛次数、本垒打次数等。列是按击球率、比赛次数、本垒打次数等进行组织的。我按列拆分数据,但现在我想创建一个函数,用于查找该赛季具有最多本垒打的球员。我能够创建一个函数(max),它可以从本垒打列表中找到最大的数字,但我希望它输出球员的名字,而不仅仅是本垒打的数量?有没有办法做到这一点,或者我应该以不同的方式拆分数据?
# importing csv file
import csv
text = open("yanks.csv").read()
# splitting rows
for row in text.split("\n"):
columns = row.split(",")
players = columns[0]
year = columns[1]
games_played = int(columns[2])
home_runs = int(columns[3])
# Function to find max amount of home runs in a list
def most_hr(list):
max = 0
for i in list:
if i > max:
max = i
return max
现在我想要获得玩家的名字作为输出,而不是跑动次数。
发布于 2018-08-09 02:33:13
从我的头顶开始,在没有看到csv文件的情况下,让你已经完成的函数从列表中返回最大的数字,并将其传递给一个类似于以下内容的函数:
def getPlayer(homeRuns):
with open('statistics.csv', 'r') as mycsv:
reader = csv.reader(mycsv, delimiter=';')
for row in reader:
if row[x] == homeRuns:
print(row[y])
在上面的代码中,您需要更改row[x]
中的x作为保存本垒打的列号,将y更改为print(row[y])
中保存您的球员姓名的列号
发布于 2018-08-09 02:55:48
不需要定义您自己的max
函数。内置名称接受key
关键字参数,您可以使用此参数查找某一列的值最高的行,然后提取max
列。
PLAYER_NAME = ... # integer index of the player_name
HOME_RUNS = ... # integer index of the number of home runs a play has
def home_runs(player):
"""
Return the number of home runs for a given player by the
number contained in the HOME_RUN column.
"""
return int(player[HOME_RUNS])
def player_name(player):
"""
Get the name column from a player row.
"""
return player[PLAYER_NAME]
def player_with_most_runs(rows):
"""
Get the name of the player with the most home runs.
"""
best_player = max(rows, key=home_runs)
return player_name(best_player)
然后,您可以将这些行从csv读取器传递到player_with_most_runs
,它将返回球员的名称。
with open('stats.csv', 'r') as stats_file:
player_records = csv.reader(stats_file)
best_player = player_with_most_runs(player_records)
https://stackoverflow.com/questions/51753279
复制相似问题