![](/img/trans.png)
[英]Python: how can I read and store data, which have changing column number, to list?
[英]How can I read a number from a file and store it as a float in a list? / Python
(这是我的第一个问题,如果不太清楚,我深表歉意)
我有一个看起来像这样的文本文件:
106.33333333333333
200.79263333333
68.214276154075
我想将每个数字放入一个列表(作为一个浮点数),然后可以用来计算平均值,最大值和总和。 (mean(),max(),sum())
我已经基于以下类似的问题回答尝试了多种变体:(简化代码)
whod = []
filename = (whouser+' '+d)
for line in filename:
numbers = line.rstrip('\n')
whod = whod + [float(numbers)]
print(whod)
然后检查
print(list)
输出:
ValueError: could not convert string to float: 's'
老实说,我没想到它会起作用,但是如果您有任何建议,那将是很好的。
谢谢。
使用列表推导和with
语句打开文件:
with open('text.txt') as text:
data = [float(i) for i in text]
然后,您可以简单地在data
列表上调用内置方法:
max_value = max(data)
sum_value = sum(data)
首先快速注意一下:正如MattDMo指出的那样,您要避免将内建函数用作变量名。 在您的示例中,多数民众赞成list
和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
如果仍然出现此错误:
ValueError: could not convert string to float: 's'
您需要确保文件中的每个项目都可以完全按原样转换为浮点数。 如果您想以更具弹性的方式读取文件:
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
这将确保您仅从文件中读取数字行。
方括号内的代码[float(n) for n in numbers_file]
将遍历numbers_file
(filename.txt)中的行,并在构建列表时将每个项目numbers_file
为float
。 然后将结果列表传递给extend
列表,以更新原始numbers
列表。 在一行代码中对这样的列表进行迭代称为列表理解 。
这是有关list
方法的python文档:
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.