如何制作一个python代码,从CSV文件中返回所有数据的信息,而不仅仅是一个单件?

时间:2014-11-30 19:39:12

标签: python file csv

我正在根据放入CSV文件的这组信息(http://www.databasebasketball.com/players/playerlist.htm)编写代码。

我想制作一个代码来确定每个玩家的BMI,然后如果他们的BMI超过30,就会认为他们是肥胖的。

如何定义一个能够为每个玩家返回信息的函数,而不仅仅是一个?

import csv

def read_csv(filename):
    """
    Reads a Comma Separated Value file,
    returns a list of rows; each row is a dictionary of columns.
    """
    with open(filename, encoding="utf_8_sig") as file:
        reader = csv.DictReader(file)
        rows = list(reader)
    return rows

# Try out the function
players = read_csv("players.csv")

# Print information on the first player, to demonstrate how
# to get to the data
from pprint import pprint
pprint(players[0])
print(players[0]["lastname"])
print(players[0]["weight"])


total_h_inches = int(players[0]["h_feet"]) * 12 + int(players[0]["h_inches"])


def obesity(bmi):
    bmi=(int(players[0]["weight"])/(total_h_inches**2))* 703
    if bmi >= 30:
        print ('player', players[0]["lastname"], 'is obese')
    else:
        print (('player', players[0]["lastname"], 'is not obese'))
print(obesity([0]))

它返回第一个玩家的信息,但我不知道如何编辑代码以便它适用于任何玩家

2 个答案:

答案 0 :(得分:1)

我能想到的最等效的代码是一个player[0]循环,它遍历整个for

列表,而不是坚持players
for i in range(len(players)):
    pprint(players[i])
    print(players[i]["lastname"])
    print(players[i]["weight"])


    total_h_inches = int(players[i]["h_feet"]) * 12 + int(players[i]["h_inches"])


    def obesity(bmi):
        bmi=(int(players[i]["weight"])/(total_h_inches**2))* 703
        if bmi >= 30:
            print ('player', players[i]["lastname"], 'is obese')
        else:
            print (('player', players[i]["lastname"], 'is not obese'))
    print(obesity([i]))

这是非常糟糕的代码:

  • 它不断为obesity循环的每次迭代定义for函数。
  • obesity函数接收bmi作为参数,但bmi实际上是在函数内计算的(因此,该参数对函数没用)

我考虑在obesitiy循环之前移动for函数并让其接受player记录来计算所述玩家的obesityplayer列表中的每个players记录都包含您需要知道的所有信息,以确定玩家是否肥胖,对吗?)。

我做的事情如下:

def is_obese(player):
    total_h_inches = int(player["h_feet"]) * 12 + int(player["h_inches"])
    bmi = (int(player["weight"])/(total_h_inches**2))* 703
    return bmi >= 30

for i in range(len(players)):
    if is_obese(players[i]):
         print ('player', players[i]["lastname"], 'is obese')
    else:
         print ('player', players[i]["lastname"], 'is not obese')

或者什么可能更清楚,而不是使用索引(数字players)走i列表,Python允许您直接遍历清单:

for player in players:
    if is_obese(player):
         print ('player', player["lastname"], 'is obese')
    else:
         print ('player', player["lastname"], 'is not obese')

您可能想查看有关Python列表的一些教程。这里有one,但那里有很多。

修改

如果您在计算玩家肥胖时遇到错误,可以将is_obese函数调用包含在try/except块中:

for player in players:
    try:
        if is_obese(player):
             print ('player', player["lastname"], 'is obese')
        else:
             print ('player', player["lastname"], 'is not obese')
    except ValueError:
        print ("I can't determine %s's obesity" % player['lastname'])

答案 1 :(得分:0)

你需要循环玩家。

def obesity(players):
    for player in players:
        total_h_inches = int(player["h_feet"]) * 12 + int(player["h_inches"])
        bmi=(int(player['weight'])/(total_h_inches**2)) * 703
        if bmi >= 30:
            print(player['lastname'], 'is obese')

然后:

obesity(players)