[英]How do I turn a string from a csv file into an integer in python?
我正在根據此信息集( 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'
我知道我離最終結果還很遙遠,但我覺得完成此步驟會有所幫助。
您需要使用內置的int()功能將字符串轉換為Integer。
total_h_inches = int(players[0]["h_feet"]) * 12
該錯誤是不言自明的:沒有像'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'
鍵
為了將英尺轉換成英寸,您應該使用players [0] ['h_feet'] * 12轉換成英寸。
由於密鑰中的'h_feet' * 12
會將密鑰名稱更改為h_feeth_feet....upto 12 times
。
另外,如果字典中的值是字符串格式,則需要像int(players[0]['h_feet'])
這樣先將其類型轉換為整數,然后乘以12
雙關語是您對關鍵誤解的預期
"h_feet"*12
計算結果為“ h_feet”重復12次。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.