在Python中,如何将列表中的所有项目都转换为浮点数? [英] In Python, how do I convert all of the items in a list to floats?

查看:840
本文介绍了在Python中,如何将列表中的所有项目都转换为浮点数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a script which reads a text file, pulls decimal numbers out of it as strings and places them into a 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?

我尝试过:

for item in list:
    float(item)

但这似乎对我不起作用。

But this doesn't seem to work for me.

推荐答案

[float(i) for i in lst]

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

to be precise, it creates a new list with float values. Unlike the map approach it will work in py3k.

这篇关于在Python中,如何将列表中的所有项目都转换为浮点数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆