I have started to look into python and am trying to grasp new things in little chunks, the latest goal i set for myself was to read a tab seperate file of floats into memory and compare values in the list and print the values if difference was as large as the user specified. I have written the following code for it so far:
#! /usr/bin/env python
value = raw_input('Please enter a mass difference:')
fh = open ( "values" );
x = []
for line in fh.readlines():
y = [float for float in line.split()]
x.append(y)
fh.close()
for i in range(0,len(x)-1):
for j in range(i,len(x)):
if x[j][0] - x[i][0] == value:
print x[i][0],x[j][0]
The compiler complains that i am not allowed to substract strings from strings (logically) but my question is … why are they strings? Shouldn’t the nested list be a list of floats as i use float for float?
Literal error:
TypeError: unsupported operand type(s) for -: 'str' and 'str'
I would greatly appreciate if someone can tell me where my reasoning goes wrong 😉
Try this in place of your list comprehension:
Explanation:
The data you read from the file are strings, to convert them to other types you need to cast them. So in your case you want to cast your values to float via
float().. which you tried, but not quite correctly/successfully. This should give you the results you were looking for.If you have other values to convert, this syntax will work:
assuming that
string_valcontains valid characters for a float, it will convert, otherwise you’ll get an exception.