[英]Importing data from a file as a float in python
I have a file, variables.txt
, when I input a float, say 7.75
, it inputs it into the file as 7.75
. 我有一个文件, variables.txt
,当我输入一个浮点数,比如7.75
,它将它作为7.75
输入到文件中。 When I get the information back from the file, I get ['7.75']
. 当我从文件中获取信息时,我得到['7.75']
。 I'm assuming this is a list. 我假设这是一个列表。 How would I be able to change ['7.75']
back to a float, 7.75, so that it can be multiplied, divided, etc. 我怎样才能将['7.75']
回浮点数7.75,以便它可以乘以,除以等等。
将列表中的第一个条目转换为float()
值:
value = float(somelist[0])
This code will open a text file with a float on each line and give you a list of float
s 此代码将打开一个文本文件,每行都有一个浮点数,并为您提供一个float
列表
with open('floats.txt', 'r') as f:
floats = []
for each in f:
floats.append(float(each.strip()))
print(floats)
you can then access each float in the list by it's index: 然后,您可以通过它的索引访问列表中的每个浮点数:
float[0] #this will give you the first entry in the list
File: 文件:
7.75
1.23
4.56
Output: 输出:
[7.75, 1.23, 4.56]
In Python, how do I convert all of the items in a list to floats? 在Python中,如何将列表中的所有项目转换为浮点数?
To reiterate, you want to loop through the list and convert all element to float values using the "float" function. 重申一下,您希望遍历列表并使用“float”函数将所有元素转换为浮点值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.