Home > front end >  Python - New to Python and I am trying to take a section of a list that is a string and make it a in
Python - New to Python and I am trying to take a section of a list that is a string and make it a in

Time:01-28

I'm trying to take this in stages, but I am stuck. Below is the task I am trying to complete, but I have run into a roadblock that I cannot seem to get over:

So far I have created the below for loops.

NBAList=[]

for line in NBAfile:
    textline =line.strip()
    items=textline.split('\t')
    NBAList.append(items)

for line in NBAList:
    print(line)

And get the below:

['1', 'Bulls', '894659', '21820', '104.3']
['2', 'Cavaliers', '843042', '20562', '100']
['3', 'Mavericks', '825901', '20143', '104.9']
['4', 'Raptors', '812863', '19825', '100.1']
['5', 'NY_Knicks', '812292', '19812', '100']

What I'm not sure of is how to get the last three numbers from strings to integers (the last one a float). I've tried several different ways but I keep getting errors. I think I can build off of what I have, but I'm just not doing it right. Any help would be greatly appreciated.

I am trying to get the basketball teams' total attendance, average attendance to be integers and capacity to be a float with 2 decimal points. I am also trying (and failing) to get the attendance totals to have the appropriate commas.

The end result I am looking for each line is -> ‘The overall attendance for Bulls was 894,659, with an average attendance of 21,820 and the capacity was 104.3%’

CodePudding user response:

Once you have the strings, convert the values you want to convert before appending anything to NBAList. For example,

NBAList = []

for line in NBAfile:
    textline =line.strip()
    items=textline.split('\t')
    items[0] = int(items[0])
    items[2:4] = map(int, items[2:4])
    item[4] = float(items[4])
    NBAList.append(items)

While the various calls to int and float are expected to succeed, based on the the assumed contents of the file, you may want to be prepared to catch the ValueError that any of them could raise.

  • Related