Skip to main content
 首页 » 编程设计

python之当项目包含括号时,将大字符串转换为 float 列表

2025年05月04日44zhengyun_ustc

我有一个包含字符串的变量 r,但我需要它是一个 float 列表。这已在本论坛中多次提及,但我似乎找不到与这种情况相符的:

>>> print r 
[0.06481481481481466, 0.06481481481481466, 0.06481481481481466, 0.0754716981132074, 0.07619047619047604, 0.07619047619047604, 0.07692307692307698, 0.07766990291262142, 0.07766990291262142, 0.07843137254901968, 0.07920792079207928, 0.07920792079207928, 0.08000000000000007, 0.08000000000000007] 
>>> type(r) 
<type 'str'> 

当我尝试拆分它时...

    >>> r.split(',') 
['[0.06481481481481466', ' 0.06481481481481466', ' 0.06481481481481466', ' 0.0754716981132074', ' 0.07619047619047604', ' 0.07619047619047604', ' 0.07692307692307698', ' 0.07766990291262142', ' 0.07766990291262142', ' 0.07843137254901968', ' 0.07920792079207928', ' 0.07920792079207928', ' 0.08000000000000007', ' 0.08000000000000007]'] 

现在 r 中的第一项和最后一项分别包含 '[' 和 ']'。很明显,为了将其转换为 float ,我需要删除它们。

这就是我所做的,但它似乎不起作用......

def stringlist_to_floatlist(e): 
    split = e.split(',') 
    l = len(split) 
    for i in split: 
        for br in ["[","]"]: 
            if br in i: 
                try: 
                    i = float(i.replace(br,"")) 
                except TypeError: 
                    continue 
            else: 
                try: 
                    i = float(i) 
                except TypeError: 
                    continue 
    return i  
 
 
>>> stringlist_to_floatlist(r) 
Traceback (most recent call last): 
  File "<stdin>", line 1, in <module> 
  File "<stdin>", line 6, in stringlist_to_floatlist 
TypeError: argument of type 'float' is not iterable 

请您参考如下方法:

>>> ast.literal_eval('[0.06481481481481466, 0.06481481481481466, 0.06481481481481466, 0.0754716981132074, 0.07619047619047604, 0.07619047619047604, 0.07692307692307698, 0.07766990291262142, 0.07766990291262142, 0.07843137254901968, 0.07920792079207928, 0.07920792079207928, 0.08000000000000007, 0.08000000000000007]') 
[0.06481481481481466, 0.06481481481481466, 0.06481481481481466, 0.0754716981132074, 0.07619047619047604, 0.07619047619047604, 0.07692307692307698, 0.07766990291262142, 0.07766990291262142, 0.07843137254901968, 0.07920792079207928, 0.07920792079207928, 0.08000000000000007, 0.08000000000000007] 
>>> ast.literal_eval('[0.06481481481481466, 0.06481481481481466, 0.06481481481481466, 0.0754716981132074, 0.07619047619047604, 0.07619047619047604, 0.07692307692307698, 0.07766990291262142, 0.07766990291262142, 0.07843137254901968, 0.07920792079207928, 0.07920792079207928, 0.08000000000000007, 0.08000000000000007]')[0] 
0.06481481481481466