(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() )
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 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:
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. In your example, thats list
and 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. The resulting list is then passed to extend
which updates the original numbers
list. Iterating over a list like this in one line of code is called a list comprehension .
Here's the python docs on list
methods:
https://docs.python.org/2/tutorial/datastructures.html#more-on-lists
my_list = my_list + [float(numbers)]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.