Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python – New to Python and I am trying to take a section of a list that is a string and make it a integer

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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%’

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading