gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 08:55:41 25 4
gpt4 key购买 nike

我有一个包含字符串的变量 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

关于python - 当项目包含括号时,将大字符串转换为 float 列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30488740/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com