【问题标题】:How do I make a python code that returns information for all pieces of data from a CSV file and not just one single piece?如何制作一个 python 代码来返回 CSV 文件中所有数据的信息,而不仅仅是一个数据?
【发布时间】:2014-11-30 19:39:12
【问题描述】:

我正在根据放入 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]))

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

【问题讨论】:

    标签: python file csv


    【解决方案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]))
    

    不过,这是非常糟糕的代码:

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

    我会考虑将obesitiy 函数移到for 循环之前,并让它接受player 记录来计算所述玩家的obesityplayers 列表中的每个player 记录都包含您需要知道玩家是否肥胖的所有信息,对吧?)。

    我会这样做:

    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')
    

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

    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'])
    

    【讨论】:

    • 我尝试了类似的方法,它适用于某些数据,但随后返回此错误:ValueError: invalid literal for int() with base 10: '8.5'
    • 什么错误?它没有被添加到评论 :-)
    • 啊,那是因为8.5 不是整数的有效字符串表示,而是一个实数(或float,而是)。看起来有些玩家的 whatever 数据不是int。检查发生这种情况的行。在该行中,您将看到 int(...whatever...)。将其更改为float(...whatever...)
    • 抱歉打扰了,但我如何只更改需要浮动的行?因为如果我将其更改为 total_h_inches = float(player["h_feet"]) * 12 + float(player["h_inches"]) 也不起作用并返回不同的错误。谢谢
    • 不用麻烦 :-)。那种类型的演员很好......你现在遇到什么错误?也许是一些关键错误?
    【解决方案2】:

    你需要循环播放器。

    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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-02-03
      • 1970-01-01
      • 2015-04-10
      • 2021-05-01
      • 2022-07-15
      • 1970-01-01
      • 2021-08-01
      相关资源
      最近更新 更多