繁体   English   中英

在 Python 中,如何将列表中的所有项目转换为浮点数?

[英]In Python, how do I convert all of the items in a list to floats?

我有一个脚本,它读取一个文本文件,将十进制数字作为字符串提取出来并将它们放入一个列表中。

所以我有这个清单:

my_list = ['0.49', '0.54', '0.54', '0.55', '0.55', '0.54', '0.55', '0.55', '0.54']

如何将列表中的每个值从字符串转换为浮点数?

我努力了:

for item in my_list:
    float(item)

但这似乎对我不起作用。

[float(i) for i in lst]

准确地说,它创建了一个带有浮点值的新列表。 map方法不同,它将在 py3k 中工作。

map(float, mylist)应该这样做。

(在 Python 3 中,map 不再返回列表对象,因此如果您想要一个新列表而不仅仅是要迭代的内容,您要么需要list(map(float, mylist) - 或使用 SilentGhost 的答案,这可以说是更 Pythonic。 )

这将是另一种方法(不使用任何循环!):

import numpy as np
list(np.float_(list_name))

float(item)做正确的事情:它将其参数转换为 float 并返回它,但它不会就地更改参数。 对您的代码的简单修复是:

new_list = []
for item in list:
    new_list.append(float(item))

相同的代码可以使用列表new_list = [float(i) for i in list]编写得更短: new_list = [float(i) for i in list]

就地更改列表:

for index, item in enumerate(list):
    list[index] = float(item)

顺便说一句,避免为变量使用list ,因为它伪装了具有相同名称的内置函数。

你甚至可以通过 numpy 做到这一点

import numpy as np
np.array(your_list,dtype=float)

这将您的列表的 np 数组返回为浮点数

您也可以将 'dtype' 设置为 int

您可以使用 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

您可以使用map()函数将列表直接转换为floats

float_list = map(float, list)

您可以使用 numpy 来避免循环:

import numpy as np
list(np.array(my_list).astype(float)

这就是我要做的。

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'>
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'>

我在我的程序中使用以下方法解决了这个问题:

number_input = float("{:.1f}".format(float(input())))
list.append(number_input)

我必须首先从浮点字符串列表中提取数字:

   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)
for i in range(len(list)): list[i]=float(list[i])

这不仅仅是一个答案,这表明您找到的第一个不一定是最好的。 Tim Pietzcker 的回答是最好的,也更有效。

import time
from typing import Iterable

def timer(func, *args, reps=1000, **kwargs):
    start = time.perf_counter()
    for i in range(reps):
        ret = func(*args, **kwargs)
    lapse = time.perf_counter() - start
    return lapse, ret

def listComprehension(to, list2comp: Iterable):
    return list(to(i) for i in list2comp)

def mapping(to, list2map: Iterable):
    return list(map(to, list2map))

if __name__ == '__main__':
    list2convert = ['1', '2', '3', '4']
    
    for func in mapping, list_comp:
        lapse, ret = timer(func, float, list2convert)
        print(func.__name__ + ': \n\tlapse:' + str(lapse) + '\n\tret:' + str(ret))

结果:

mapping:
    lapse:0.005934100000000164
    ret:[1.0, 2.0, 3.0, 4.0]
list_comp:
    lapse:0.05731120000000001
    ret:[1.0, 2.0, 3.0, 4.0]

暂无
暂无

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

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