繁体   English   中英

将字符串列表转换为整数 PYTHON

[英]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)

我正在尝试将 CSV 文件中的数据转换为整数。

我试过了

FTHG = int(row[4])
FTAG = int(row[5])

但得到以下错误:

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'

为了对 CSV 文件中的足球数据进行一些分析,代表进球数的值需要存储为整数。 由于 CSV 文件中的所有数据都是我需要转换的字符串数据。 我使用的语法确实在我的循环之外工作。

试试看:

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.

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