简体   繁体   English

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

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

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:所以我有这个清单:

my_list = ['0.49', '0.54', '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 my_list:
    float(item)

But this doesn't seem to work for me.但这似乎对我不起作用。

[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.map方法不同,它将在 py3k 中工作。

map(float, mylist) should do it. map(float, mylist)应该这样做。

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

This would be an other method (without using any loop!):这将是另一种方法(不使用任何循环!):

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

float(item) do the right thing: it converts its argument to float and and return it, but it doesn't change argument in-place. float(item)做正确的事情:它将其参数转换为 float 并返回它,但它不会就地更改参数。 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]相同的代码可以使用列表new_list = [float(i) for i in list]编写得更短: 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.顺便说一句,避免为变量使用list ,因为它伪装了具有相同名称的内置函数。

you can even do this by numpy你甚至可以通过 numpy 做到这一点

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

this return np array of your list as float这将您的列表的 np 数组返回为浮点数

you also can set 'dtype' as int您也可以将 'dtype' 设置为 int

You can use numpy to convert a list directly to a floating array or matrix.您可以使用 numpy 将列表直接转换为浮动数组或矩阵。

    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如果要将整数数组转换为浮点数组,则向其添加 0.

    list_float = np.array(list_ex) + 0. # This is a numpy floating array

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

float_list = map(float, list)

you can use numpy to avoid looping:您可以使用 numpy 来避免循环:

import numpy as np
list(np.array(my_list).astype(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'>
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:您可以使用 numpy 同时将此列表转换为浮点数组:

    my_list = np.array(my_list).astype(np.float)

    print(type(my_list), type(my_list[0]))  
    # <class 'numpy.ndarray'> <class 'numpy.float64'>

I have solve this problem in my program using:我在我的程序中使用以下方法解决了这个问题:

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

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:最后将所有浮点数分配给数据帧作为 float64:

   df4['fscore'] = np.array(ad,dtype=float)
for i in range(len(list)): list[i]=float(list[i])

More than an answer, this shows that always the first one you find is not necessarily the best.这不仅仅是一个答案,这表明您找到的第一个不一定是最好的。 Tim Pietzcker answer is the best and more efficient. 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))

Results:结果:

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.

相关问题 如何将输入字符串转换为 python 中的浮点数列表 - How do I convert an input string to a list of floats in python 如何在Python中拉伸浮点列表? - How do I stretch a list of floats in Python? 如何使用Python将字符串列表转换为浮点列表? - How do you convert a list of strings to a list of floats using Python? 如何将浮点数列表转换为百分比列表? - How do I convert a list of floats into a list of percentages? 如何将列表列表中的所有字符串转换为浮点数 - How to convert all the strings in a list of a list to floats 如何将由整数和浮点数组成的列表中的字符串列表转换为整数和浮点数? - How do I convert a list of strings in a list composed of ints and floats to both ints and floats? 如何在Python中将unicode字符转换为浮点数? - How do I convert unicode characters to floats in Python? 如何将 a.csv 中的项目转换为 python 中的列表 - How do I convert items in a .csv to a list in python 在Python中,如何将列表列表中的字符串转换为其他类型,如整数,浮点数,布尔值等? - In Python how do you convert strings in a list of list to other types, such as ints, floats, booleans, etc? 在 python - 我如何将项目转换为字典? - In python - how do I convert items to dict?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM