【发布时间】:2014-11-30 17:44:08
【问题描述】:
我正在根据这组信息 (http://www.databasebasketball.com/players/playerlist.htm) 编写代码,并将其放入 CSV 文件中。
我想做一个代码,确定每个玩家的BMI,然后如果他们的BMI超过30,就会认为他们肥胖。
但是,我必须将球员的身高(以英尺为单位)转换为以英寸为单位的高度,如果不更改原始 CSV 文件,我不确定如何做到这一点。
到目前为止我有:
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 = print(players[0]["h_feet"*12])
但它返回一个错误
Traceback (most recent call last):
File "C:\Python34\hw5.py", line 24, in <module>
h_feet = print(players[0]["h_feet"*12])
KeyError: 'h_feeth_feeth_feeth_feeth_feeth_feeth_feeth_feeth_feeth_feeth_feeth_feet'
我知道我离最终结果还很远,但我觉得完成这一步会有很大帮助。
【问题讨论】:
-
错误是不言自明的:没有像 'h_feeth_feeth_feeth_feeth_feeth_feeth_feeth_feeth_feeth_feeth_feeth_feet' 这样的键可能是您正在寻找球员[0]['h_feet'] * 12 以转换为英寸。
-
请不要在人们回答后更改您的问题 - 这会让用户感到困惑,因为已经给出的答案不再与问题相关。相反,提出一个新问题(一旦你花了更多时间研究你的新问题。)