【问题标题】:How do I turn a string from a csv file into an integer in python?python - 如何将csv文件中的字符串转换为python中的整数?
【发布时间】: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 以转换为英寸。
  • 请不要在人们回答后更改您的问题 - 这会让用户感到困惑,因为已经给出的答案不再与问题相关。相反,提出一个新问题(一旦你花了更多时间研究你的新问题。)

标签: python css file csv


【解决方案1】:

您需要使用内置的 int() 功能将字符串转换为整数...

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

【讨论】:

    【解决方案2】:

    错误是不言自明的:没有像'h_feeth_feeth_feeth_feeth_feeth_feeth_feeth_feeth_feeth_feeth_feeth_feet' 这样的键

    为了将英尺转换为英寸 你应该使用 player[0]['h_feet'] * 12 转换成英寸。

    由于密钥中的'h_feet' * 12会将密钥名称更改为h_feeth_feet....upto 12 times

    另外,如果字典中的Value是字符串格式,你需要先将其类型转换为整数,如int(players[0]['h_feet']),然后乘以12

    【讨论】:

      【解决方案3】:

      关键的误解,双关语,是你所期望的

      "h_feet"*12
      

      计算结果为“h_feet”重复了 12 次。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-10-31
        • 1970-01-01
        • 2010-12-27
        相关资源
        最近更新 更多