Home > Back-end >  How to change a string value that is in a list to a float in Python
How to change a string value that is in a list to a float in Python

Time:09-21

I am trying to convert numerical strings in a list over to a float, but am having difficulty, likely due to the fact that it is within a list of lists. I can't pinpoint a fix. The list will be later converted over to a dictionary

My list format looks like this:

[['PokedexNumber','Name','Type','Total','HP','Attack','Defense','SpecialAttack','SpecialDefense','Speed'],
 ['001','Bulbasaur','GrassPoison','318','45',
  '49','49','65','65','45'],
 ['002', 'Ivysaur', 'GrassPoison', '405', '60', '62', '63', '80', '80', '60']]

My code is:

for i in newest_list:
   try:
       float(i)
   except ValueError:
       i

The error I get is:

TypeError: float() argument must be a string or a number, not 'list'

CodePudding user response:

Use a simple list comprehension and the str.isnumeric method:

[[float(item) if item.isnumeric() else item for item in l] for l in newest_list]

output:

[['PokedexNumber', 'Name', 'Type', 'Total', 'HP', 'Attack',
  'Defense',  'SpecialAttack', 'SpecialDefense', 'Speed'],
 [1.0, 'Bulbasaur', 'GrassPoison', 318.0, 45.0, 49.0, 49.0, 65.0, 65.0, 45.0],
 [2.0, 'Ivysaur', 'GrassPoison', 405.0, 60.0, 62.0, 63.0, 80.0, 80.0, 60.0]]

CodePudding user response:

That's because you have a 2D array of size 3Xn

You need to add another loop to iterate over each inner list

for l in newest_list:
    for string in inner_list:
        try:
            float(string)
        except ValueError:
            pass

CodePudding user response:

Since you have a list of lists, try adding another for loop to iterate over the inner list:

L = [['PokedexNumber', 'Name', 'Type', 'Total', 'HP', 'Attack', 'Defense', 'SpecialAttack', 'SpecialDefense', 'Speed'],
     ['001', 'Bulbasaur', 'GrassPoison', '318', '45',
      '49', '49', '65', '65', '45'],
     ['002', 'Ivysaur', 'GrassPoison', '405', '60', '62', '63', '80', '80', '60']]

for i in L:
    ## Added
    for j in i:
    ## End
       try:
           float(j)
       except ValueError:
            j

This becomes even easier with list comprehensions:

def try_parse_float(x):
    try:
        return float(x)
    except ValueError:
        return x

vals = [(try_parse_float(j)) for i in L for j in i]

or, inspired by @mozway's answer:

vals = [float(j) if j.isnumeric() else j for i in L for j in i]

CodePudding user response:

Your list is actually a list of lists, instead of a list, not a string or numer.

A working for loop would look like this

for l in newest_list:
    for i in l:
        try:
            float(i)
        except ValueError:
            pass # using pass here as just using i doesn't do anything

CodePudding user response:

With a second loop you can access the lists in the list. Than check if the values in the inner list can be converted to float. If yes, replace string list element with type float.

for idx,value in enumerate(newest_list):
    for idx2, value2 in enumerate(value):
        try:
            float(value2)
            newest_list[idx][idx2] = float(value2)
        except ValueError:
            pass

# To check the new types of the variables:
for idx,value in enumerate(newest_list):
    for idx2, value2 in enumerate(value):
        print(type(value2))

  • Related