简体   繁体   English

列表列表:循环将字符串转换为浮点数

[英]List of lists: looping to convert strings to floats

I have a data object of the type: list[lists['string', 'string', floats]] , but actually the floats are strings too, which I want to convert to floats.我有一个类型为 object 的数据: list[lists['string', 'string', floats]] ,但实际上浮点数也是字符串,我想将其转换为浮点数。 I tried the following but for some reason it still loops over the first two elements in the internal lists, but the if statement seems correct?我尝试了以下但出于某种原因它仍然循环内部列表中的前两个元素,但 if 语句似乎正确? Does anyone know what I'm doing wrong?有谁知道我做错了什么?

list_of_lists = [
    ['bla1', 'bla2', '1.', '2.', '3.', '4.'],
    ['bla3', 'bla4', '5.', '6.', '7.', '8.']
    ]

for idx_datapoint, datapoint in enumerate(list_of_lists):
    print(f'{datapoint = }')
    for idx_feature, feature_val in enumerate(datapoint):
        if idx_feature in (0, 1):
            print(f'{idx_feature = }, {feature_val = }')
            print(f'{float(feature_val) = }')
            list_of_lists[idx_datapoint][idx_feature] = float(feature_val)

Thank you for your help in advance,: I think I'm overlooking something small, so sorry in advance :D提前感谢您的帮助:我想我忽略了一些小东西,提前抱歉:D

Keep in mind that some of the values of the lists have letters in them, so they cant be changed into floats.请记住,列表的某些值中包含字母,因此无法将它们更改为浮点数。 Other than that, this is how I would do it:除此之外,这就是我的做法:

list_of_lists = [
    ['bla1', 'bla2', '1.', '2.', '3.', '4.'],
    ['bla3', 'bla4', '5.', '6.', '7.', '8.']
    ]

for i, list in enumerate(list_of_lists):
    for i2, v in enumerate(list):
        try:
            list_of_lists[i][i2] = float(v)
        except ValueError:
            pass  # change to whatever you want to do if you cant change it

I just tested it and it seems to work fine.我刚刚对其进行了测试,它似乎工作正常。 Just change the 'pass' line to whatever you want to do with the values that have letters in them (like removing them or removing the letters).只需将“通过”行更改为您想要对其中包含字母的值执行的任何操作(例如删除它们或删除字母)。

A simple try block might do the trick:一个简单的 try 块可能会成功:

list1 = ['hello', '1.3', 1, 2, 3]
list2 = []
# print(list1[0].isfloat())
for i in list1:
    try:
        list2.append(float(i))
    except ValueError:
        list2.append(i)
print(list2)

Output: Output:

['hello', 1.3, 1.0, 2.0, 3.0]

Your missing a not after the if statement, because you don't want the first two elements from your datapoint .您在 if 语句之后缺少一个not ,因为您想要datapoint的前两个元素。 You should do:你应该做:

if not idx_feature in (0, 1):

I'd say:我会说:

"""
Checks if argument is floatable
"""
def is_float(element: any) -> bool:
    try:
        float(element)
        return True
    except ValueError:
        return False

"""
iterates over the list of lists
"""
for lst in list_of_lists:
 list_of_lists  = [l if not is_float(l) else float(l) for l in lst]

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

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