简体   繁体   中英

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.

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. As all data in a CSV file is string data I need to convert. 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

# ... #

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM