简体   繁体   English

如何从文件中读取数字并将其作为浮点数存储在列表中? / Python

[英]How can I read a number from a file and store it as a float in a list? / Python

(this is my first ever question, so I apologise if it's not very clear) (这是我的第一个问题,如果不太清楚,我深表歉意)

I have a text file which looks something like this: 我有一个看起来像这样的文本文件:

106.33333333333333
200.79263333333
68.214276154075

and I would like to put each number into a list (as a float) which can then be used to work out the average, maximum and sum. 我想将每个数字放入一个列表(作为一个浮点数),然后可以用来计算平均值,最大值和总和。 ( mean() , max() , sum() ) (mean(),max(),sum())


I've tried a number of variations based on similar question responses of: (simplified code) 我已经基于以下类似的问题回答尝试了多种变体:(简化代码)

    whod = []

    filename = (whouser+' '+d)

    for line in filename:
        numbers = line.rstrip('\n')
        whod = whod + [float(numbers)]

    print(whod)

then to check, 然后检查

print(list)

Output: 输出:

ValueError: could not convert string to float: 's'

To be honest I didn't expect it work but if you have any suggestions that would be great. 老实说,我没想到它会起作用,但是如果您有任何建议,那将是很好的。

Thank you. 谢谢。

Use a list comprehension and a with statement to open the file: 使用列表推导和with语句打开文件:

with open('text.txt') as text:
    data = [float(i) for i in text]

Then you can simply call your built-in methods on the data list: 然后,您可以简单地在data列表上调用内置方法:

max_value = max(data)
sum_value = sum(data)

First a quick note: As MattDMo pointed out, you want to avoid using builtins as variable names. 首先快速注意一下:正如MattDMo指出的那样,您要避免将内建函数用作变量名。 In your example, thats list and file 在您的示例中,多数民众赞成listfile

https://docs.python.org/2/library/functions.html#list https://docs.python.org/2/library/functions.html#file https://docs.python.org/2/library/functions.html#list https://docs.python.org/2/library/functions.html#file


with open('filename.txt','r') as numbers_file:
    numbers = [float(n) for n in numbers_file]

print 'numbers: %s' % numbers
numbers_max = max(numbers)
print 'max: %s' % numbers_max
numbers_sum = sum(numbers)
print 'sum: %s' % numbers_sum
numbers_mean = numbers_sum / float(len(numbers))
print 'mean: %s' % numbers_mean

If you are still getting this error: 如果仍然出现此错误:

ValueError: could not convert string to float: 's'

You need to make sure that every item in the file can be cast as a float exactly as is. 您需要确保文件中的每个项目都可以完全按原样转换为浮点数。 If you want to read the file in a more resilient way: 如果您想以更具弹性的方式读取文件:

numbers = []
with open('filename.txt','r') as numbers_file:
    for line in numbers_file:
        try:
            num = float(line.strip())
            numbers.append(num)
        except ValueError:
            continue

This will ensure that you only read the lines from the file that are numbers. 这将确保您仅从文件中读取数字行。


The code inside the brackets, [float(n) for n in numbers_file] will iterate over the lines in the numbers_file (filename.txt) and cast each item as float while building the list. 方括号内的代码[float(n) for n in numbers_file]将遍历numbers_file (filename.txt)中的行,并在构建列表时将每个项目numbers_filefloat The resulting list is then passed to extend which updates the original numbers list. 然后将结果列表传递给extend列表,以更新原始numbers列表。 Iterating over a list like this in one line of code is called a list comprehension . 在一行代码中对这样的列表进行迭代称为列表理解

Here's the python docs on list methods: 这是有关list方法的python文档:

https://docs.python.org/2/tutorial/datastructures.html#more-on-lists https://docs.python.org/2/tutorial/datastructures.html#more-on-lists

my_list = my_list + [float(numbers)]

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

相关问题 Python:如何读取和存储列号不断变化的数据以列出? - Python: how can I read and store data, which have changing column number, to list? 如何浮动从Python 3.5中的文件读取的列表元素? - How do I float an element of a list that is read from a file in Python 3.5? 如何在Python中的数字内存储数字列表? - How can I store a list of number inside a number in Python? 如何从Python中读取文件列表? - How can I read a list from a file in Python? 如何在会话之间存储和读取Django模型对象的Python列表? - how can I store and read a Python list of Django model objects from and to the session? 从文件读取行但存储为列表(python) - read line from file but store as list (python) 如何将文件读入包含行号的元组列表? - How can I read a file into a list of tuples including the line number? 如何将巨大的python列表存储为文件,然后在python中将文件作为列表读取? - How to store HUGE python list as a file and then read the file as a list in python? 如何快速读取 Python 中二进制文件的最后一个浮点数 - How to read last float number of binary file in Python in a fast way 如何从文件中读取python中的数组列表并将其放入数组列表中? - How can i read a list of arrays in python from a file and put it in a list of array?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM