简体   繁体   中英

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

g = [('Books', '10.000'),('Pen', '10'),('test', 'a')]

Here '10.000' and '10' are strings

How to convert to below format, string to float

Expected out

[('Books', 10.000),('Pen', 10),('test', 'a')]

Here 10.000 and 10 are floats and a has to be string

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

I got error AttributeError: 'tuple' object has no attribute 'isalpha'

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.

在此处输入图像描述

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.

data = [('Books', '10.000'),('Pen', 10)]
print([(a,float(b)) for a,b in data]) 

this can help iterate through a loop and convert you second item in tuple to float

What exactly is the number of 10,000 converted? There are 2 options. 10.0 or 10000.0

It will not work in cases involving this letter.

referance data data = [('Books', '10.000'),('Pen', 10)]

step: 10000.0

print([(key,float(str(value).replace('.',''))) for key, value in data])
# [('Books', 10000.0), ('Pen', 10.0)]

step: 10.0 this is already given above. But let me take a note to avoid confusion.

print([(key, float(str(value))) for key, value in data])
# [('Books', 10.0), ('Pen', 10.0)]

Your current approach tries to use the.isalpha() function on a tuple rather than a string. The error is telling you that the tuple object does not have the isalpha() function built in.

Using your approach, you'd need to decouple the tuple so that you could check the string inside each tuple, then run your logic. In the code, I abstracted your checking logic out in a function to try to show more clearly that you'd need to run it twice for each tuple in the list.

def convert_to_proper_type(value):
    if value.isalpha():
        value = str(value)
    elif value.isdigit():
        value = int(value)
    else:
        value = float(value)
    return value

result = [('Books', '10.000'),('Pen', '10'),('test', 'a')]
newresult = []

for (value_one, value_two) in result:
    # If all chars in both are alphabets
    value_one = convert_to_proper_type(value_one)
    value_two = convert_to_proper_type(value_two)
    newresult.append((value_one, value_two))

print(newresult)
# [('Books', 10.0), ('Pen', 10), ('test', 'a')]

I would try with the following:

g = [('Books', float('10.000')),('Pen', float('10')),('test', 'a')]

Try this

list_ = [('Books', '10.000'),('Pen', '10'),('test', 'a')]

def fix_list(list_):
    def check_and_convert(val_1, val_2):
        try:
            return val_1, float(val_2)
        except:
            return val_1, val_2

    ret_list = []
    for val_1, val_2 in list_:
        ret_list.append(check_and_convert(val_1, val_2))
    return ret_list


print(fix_list(list_))
# >>> [('Books', 10.0), ('Pen', 10.0), ('test', 'a')]
# Helper Function check if string is a number
def is_number(n:str):
    try:
        float(n)
    except ValueError:
        return False
    return True

# Filter the list of numbers using the following 
>>> g = [('Books', '10.000'),('Pen', '10'),('test', 'a')]
>>> [float(char) if is_number(char) else char for char in map(lambda x:x[1],g)]
>>> [10.0, 10.0, 'a']
>>> # If only numbers are needed
>>> [float(char) if is_number(char) for char in map(lambda x:x[1],g)]
>>> [10.0, 10.0]

there is many ways to make a working solution, but I think that the best is to correct your solution

in your code

for x in result:

the values of x are: ('Books', '10.000'),('Pen', '10'),('test', 'a') so we need to modify the condition to look at the second element of each tuple

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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