[英]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
在您的示例中,多数民众赞成
list
和file
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_file
为float
。 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.