问题:在Python中,如何将列表中的所有项目都转换为浮点数?
我有一个脚本,该脚本读取文本文件,将十进制数字作为字符串从中提取出来并将它们放入列表中。
所以我有这个清单:
['0.49', '0.54', '0.54', '0.54', '0.54', '0.54', '0.55', '0.54', '0.54', '0.54',
'0.55', '0.55', '0.55', '0.54', '0.55', '0.55', '0.54', '0.55', '0.55', '0.54']
如何将列表中的每个值从字符串转换为浮点数?
我努力了:
for item in list:
float(item)
但这似乎对我不起作用。
I have a script which reads a text file, pulls decimal numbers out of it as strings and places them into a list.
So I have this list:
['0.49', '0.54', '0.54', '0.54', '0.54', '0.54', '0.55', '0.54', '0.54', '0.54',
'0.55', '0.55', '0.55', '0.54', '0.55', '0.55', '0.54', '0.55', '0.55', '0.54']
How do I convert each of the values in the list from a string to a float?
I have tried:
for item in list:
float(item)
But this doesn’t seem to work for me.
回答 0
[float(i) for i in lst]
确切地说,它将创建一个带有浮点值的新列表。与该map
方法不同,它将在py3k中工作。
[float(i) for i in lst]
to be precise, it creates a new list with float values. Unlike the map
approach it will work in py3k.
回答 1
map(float, mylist)
应该这样做。
(在Python 3中,map不再返回列表对象,因此,如果您想要一个新列表而不只是要迭代的内容,则需要list(map(float, mylist)
-或使用SilentGhost的答案(可以说是更Python的)。)
map(float, mylist)
should do it.
(In Python 3, map ceases to return a list object, so if you want a new list and not just something to iterate over, you either need list(map(float, mylist)
– or use SilentGhost’s answer which arguably is more pythonic.)
回答 2
float(item)
做正确的事情:它将其参数转换为float并返回,但不会就地更改参数。您的代码的一个简单修正是:
new_list = []
for item in list:
new_list.append(float(item))
使用列表理解,可以将相同的代码写得更短: new_list = [float(i) for i in list]
要就地更改列表:
for index, item in enumerate(list):
list[index] = float(item)
顺便说一句,请避免将其list
用于变量,因为它会伪装具有相同名称的内置函数。
float(item)
do the right thing: it converts its argument to float and and return it, but it doesn’t change argument in-place. A simple fix for your code is:
new_list = []
for item in list:
new_list.append(float(item))
The same code can written shorter using list comprehension: new_list = [float(i) for i in list]
To change list in-place:
for index, item in enumerate(list):
list[index] = float(item)
BTW, avoid using list
for your variables, since it masquerades built-in function with the same name.
回答 3
这将是另一种方法(不使用任何循环!):
import numpy as np
list(np.float_(list_name))
This would be the an other method (without using any loop!):
import numpy as np
list(np.float_(list_name))
回答 4
你甚至可以通过numpy做到这一点
import numpy as np
np.array(your_list,dtype=float)
返回列表的np数组为float
您也可以将’dtype’设置为int
you can even do this by numpy
import numpy as np
np.array(your_list,dtype=float)
this return np array of your list as float
you also can set ‘dtype’ as int
回答 5
您可以使用numpy将列表直接转换为浮动数组或矩阵。
import numpy as np
list_ex = [1, 0] # This a list
list_int = np.array(list_ex) # This is a numpy integer array
如果要将整数数组转换为浮点数组,请添加0。
list_float = np.array(list_ex) + 0. # This is a numpy floating array
You can use numpy to convert a list directly to a floating array or matrix.
import numpy as np
list_ex = [1, 0] # This a list
list_int = np.array(list_ex) # This is a numpy integer array
If you want to convert the integer array to a floating array then add 0. to it
list_float = np.array(list_ex) + 0. # This is a numpy floating array
回答 6
这就是我要做的。
my_list = ['0.49', '0.54', '0.54', '0.54', '0.54', '0.54', '0.55', '0.54',
'0.54', '0.54', '0.55', '0.55', '0.55', '0.54', '0.55', '0.55', '0.54',
'0.55', '0.55', '0.54']
print type(my_list[0]) # prints <type 'str'>
my_list = [float(i) for i in my_list]
print type(my_list[0]) # prints <type 'float'>
This is how I would do it.
my_list = ['0.49', '0.54', '0.54', '0.54', '0.54', '0.54', '0.55', '0.54',
'0.54', '0.54', '0.55', '0.55', '0.55', '0.54', '0.55', '0.55', '0.54',
'0.55', '0.55', '0.54']
print type(my_list[0]) # prints <type 'str'>
my_list = [float(i) for i in my_list]
print type(my_list[0]) # prints <type 'float'>
回答 7
import numpy as np
my_list = ['0.49', '0.54', '0.54', '0.54', '0.54', '0.54', '0.55', '0.54', '0.54', '0.54', '0.55', '0.55', '0.55', '0.54', '0.55', '0.55', '0.54',
'0.55', '0.55', '0.54']
print(type(my_list), type(my_list[0]))
# <class 'list'> <class 'str'>
将类型显示为字符串列表。您可以使用numpy同时将此列表转换为浮点数数组:
my_list = np.array(my_list).astype(np.float)
print(type(my_list), type(my_list[0]))
# <class 'numpy.ndarray'> <class 'numpy.float64'>
import numpy as np
my_list = ['0.49', '0.54', '0.54', '0.54', '0.54', '0.54', '0.55', '0.54', '0.54', '0.54', '0.55', '0.55', '0.55', '0.54', '0.55', '0.55', '0.54',
'0.55', '0.55', '0.54']
print(type(my_list), type(my_list[0]))
# <class 'list'> <class 'str'>
which displays the type as a list of strings. You can convert this list to an array of floats simultaneously using numpy:
my_list = np.array(my_list).astype(np.float)
print(type(my_list), type(my_list[0]))
# <class 'numpy.ndarray'> <class 'numpy.float64'>
回答 8
我必须首先从浮点字符串列表中提取数字:
df4['sscore'] = df4['simscore'].str.findall('\d+\.\d+')
然后将每个转换为浮点数:
ad=[]
for z in range(len(df4)):
ad.append([float(i) for i in df4['sscore'][z]])
最后,将所有浮点数分配给数据框为float64:
df4['fscore'] = np.array(ad,dtype=float)
I had to extract numbers first from a list of float strings:
df4['sscore'] = df4['simscore'].str.findall('\d+\.\d+')
then each convert to a float:
ad=[]
for z in range(len(df4)):
ad.append([float(i) for i in df4['sscore'][z]])
in the end assign all floats to a dataframe as float64:
df4['fscore'] = np.array(ad,dtype=float)
回答 9
我已经在我的程序中使用以下方法解决了这个问题:
number_input = float("{:.1f}".format(float(input())))
list.append(number_input)
I have solve this problem in my program using:
number_input = float("{:.1f}".format(float(input())))
list.append(number_input)
回答 10
for i in range(len(list)): list[i]=float(list[i])
for i in range(len(list)): list[i]=float(list[i])
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。