How to convert data type for list of tuples string to float

With the 'a' value (ie a value not convertible to float) included, you can do, relying on this answer:

def tofloat(price):
    try: return float(price)
    except ValueError: return price #we do this when price is not convertable to float

After, proceed with a list comprehension:

result = [(item, tofloat(price)) for item, price in g]

result will be:

[('Books', 10.0), ('Pen', 10.0), ('test', 'a')]

There is no difference between float 10 and 10.000, so if you want 10 and 10.000 to appear in distinct ways you should keep them strings.



Reflection on comments

To check that the numerical values are float and not int, we can do:

print([type(number) for item, number in result])

giving an output:

[<class 'float'>, <class 'float'>, <class 'str'>]

as required.

enter image description here

Notebook avaliable here.


you have a problem in your code because the x that you are using is a tuple. The elements of the list you provided are tuples type (String,String) so you need one more iteration on the elemts of the tuples. I have modified your code to :

newresult = []
for tuple in result:
    temp = []
    for x in tuple:
        if x.isalpha():
            temp.append(x)
        elif x.isdigit():
            temp.append(int(x))
        else:
            temp.append(float(x))
    newresult.append((temp[0],temp[1]))
print(newresult)

I have tested the code :

 //input 
 result= [('Books', '10.000'),('Pen', '10'),('test', 'a')]
 //output
 [('Books', 10.0), ('Pen', 10), ('test', 'a')]

You need to use the right value from each tuple:

for first_value, second_value in result:    
    if isinstance(second_value, int):
        ...
    else isinstance(second_value, float):
        ...
 
  1. first_value will be "Books"
  2. second_value will be '10.000'

But it's not clear what you are trying to accomplish.

Tags:

Python

Tuples