[英]Converting list of strings to integers PYTHON
import csv
with open('Football_data.csv') as csvfile:
readCSV = csv.reader(csvfile, delimiter=',')
dates = []
homeTeam = []
awayTeam = []
fullTimeHomeGoals = []
fullTimeAwayGoals = []
fullTimeResult = []
for row in readCSV:
#ignore row[0]
date = row[1]
home = row[2]
away = row[3]
FTHG = row[4]
FTAG = row[5]
FTR = row[6]
dates.append(date)
homeTeam.append(home)
awayTeam.append(away)
fullTimeHomeGoals.append(FTHG)
fullTimeAwayGoals.append(FTAG)
fullTimeResult.append(FTR)
print(date, home,FTHG, FTAG, away)
I am trying to convert the data from my CSV file to an integer.我正在尝试将 CSV 文件中的数据转换为整数。
I have tried我试过了
FTHG = int(row[4])
FTAG = int(row[5])
But get the following error:但得到以下错误:
Traceback (most recent call last):
File "C:/Users/*****/PycharmProjects/untitled/first.py", line 19, in
<module>
FTHG = int(row[4])
ValueError: invalid literal for int() with base 10: 'FTHG'
In order to do some analysis of the football data in the CSV file the values representing goals scored need to be stored as integers.为了对 CSV 文件中的足球数据进行一些分析,代表进球数的值需要存储为整数。 As all data in a CSV file is string data I need to convert.
由于 CSV 文件中的所有数据都是我需要转换的字符串数据。 The syntax I have used does work outside my loop.
我使用的语法确实在我的循环之外工作。
Try that:试试看:
import csv
with open('Football_data.csv') as csvfile:
readCSV = csv.reader(csvfile, delimiter=',')
################ This is the header of each columns
next(readCSV) ## This line reads it so it is not read
################ when iterating in the for loop
# ... #
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.