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

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

问题描述

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

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

我试过了:

for item in my_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天全站免登陆