将逗号分隔的浮点数转换为列表?

时间:2022-01-11 00:18:09

I need to define a function txtnum(L) that takes a string of comma separated floats such as "1.5,2.5,3.5" as a parameter and converts it into a list [1.5, 2.5, 3.5].

我需要定义一个函数txtnum(L),它接受一串逗号分隔的浮点数,如“1.5,2.5,3.5”作为参数,并将其转换为列表[1.5,2.5,3.5]。

I have tried using .split(), .join(), map(), etc and cannot get anything to return a list that does NOT include quotations. I'm pretty new to Python and a little lost here.

我已经尝试过使用.split(),. join(),map()等,并且无法获取任何内容来返回不包含引号的列表。我对Python很陌生,在这里有点迷失。

How would I go about doing this?

我该怎么做呢?

3 个解决方案

#1


3  

You need to convert the datatype of splitted vars because splitting alone string gives you a list of strings.

您需要转换拆分变量的数据类型,因为单独拆分字符串会为您提供字符串列表。

>>> s = "1.5,2.5,3.5"
>>> [float(i) for i in s.split(',')]
[1.5, 2.5, 3.5]
>>> 

or

>>> map(float, s.split(','))
[1.5, 2.5, 3.5]

#2


0  

1.5,2.5,3.5 is a valid tuple literal in Python (without parentheses, yes, but it doesn't matter), so you can use ast.literal_eval on it:

1.5,2.5,3.5是Python中的有效元组文字(没有括号,是的,但没关系),所以你可以在其上使用ast.literal_eval:

In [1]: import ast

In [2]: s = '1.5,2.5,3.5'

In [3]: ast.literal_eval(s)
Out[3]: (1.5, 2.5, 3.5)

If you really need a list, that's easy, too:

如果你真的需要一个清单,那也很简单:

In [4]: list(ast.literal_eval(s))
Out[4]: [1.5, 2.5, 3.5]

#3


-1  

Try this out:

试试这个:

s = "1.5,2.5,3.5"
strArr = s.split(',')
import numpy as np
x = np.array(strArr, dtype='|S4')
arrFloat = x.astype(np.float)
print arrFloat

#1


3  

You need to convert the datatype of splitted vars because splitting alone string gives you a list of strings.

您需要转换拆分变量的数据类型,因为单独拆分字符串会为您提供字符串列表。

>>> s = "1.5,2.5,3.5"
>>> [float(i) for i in s.split(',')]
[1.5, 2.5, 3.5]
>>> 

or

>>> map(float, s.split(','))
[1.5, 2.5, 3.5]

#2


0  

1.5,2.5,3.5 is a valid tuple literal in Python (without parentheses, yes, but it doesn't matter), so you can use ast.literal_eval on it:

1.5,2.5,3.5是Python中的有效元组文字(没有括号,是的,但没关系),所以你可以在其上使用ast.literal_eval:

In [1]: import ast

In [2]: s = '1.5,2.5,3.5'

In [3]: ast.literal_eval(s)
Out[3]: (1.5, 2.5, 3.5)

If you really need a list, that's easy, too:

如果你真的需要一个清单,那也很简单:

In [4]: list(ast.literal_eval(s))
Out[4]: [1.5, 2.5, 3.5]

#3


-1  

Try this out:

试试这个:

s = "1.5,2.5,3.5"
strArr = s.split(',')
import numpy as np
x = np.array(strArr, dtype='|S4')
arrFloat = x.astype(np.float)
print arrFloat