简体   繁体   English

如何将元组字符串列表的数据类型转换为浮点数

[英]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这里'10.000''10'是字符串

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这里10.00010是浮点数, a必须是字符串

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'我收到错误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 :包含'a'值(即不可转换为浮点数的值),您可以依靠这个答案

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: result将是:

[('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. float 10 和 10.000 之间没有区别,因此如果您希望 10 和 10.000 以不同的方式出现,您应该将它们保留为字符串。



Reflection on comments对评论的反思

To check that the numerical values are float and not int , we can do:要检查数值是float而不是int ,我们可以这样做:

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

giving an output:给出 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.您的代码有问题,因为您使用的 x 是一个元组。 The elements of the list you provided are tuples type (String,String) so you need one more iteration on the elemts of the tuples.您提供的列表的元素是元组类型 (String,String),因此您需要对元组的元素再进行一次迭代。 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" first_value 将是“书籍”
  2. second_value will be '10.000' second_value 将是“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?转换的 10,000 的数量到底是多少? There are 2 options.有 2 个选项。 10.0 or 10000.0 10.0 或 10000.0

It will not work in cases involving this letter.它不适用于涉及这封信的情况。

referance data data = [('Books', '10.000'),('Pen', 10)]参考数据data = [('Books', '10.000'),('Pen', 10)]

step: 10000.0步长: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. step: 10.0 这已经在上面给出了。 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.isalpha() function。 The error is telling you that the tuple object does not have the isalpha() function built in.该错误告诉您元组 object 没有内置 isalpha() function。

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.在代码中,我在 function 中抽象出您的检查逻辑,以尝试更清楚地表明您需要为列表中的每个元组运行两次。

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 x 的值是: ('Books', '10.000'),('Pen', '10'),('test', 'a') 所以我们需要修改条件以查看每个元素的第二个元素元组

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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