a=['0.0','123.34'] #list
b=['0.0','123.34']
def isclose(a, b, rel_tol=1e-09, abs_tol=0.0):
return abs(a-b) <= max(rel_tol * max(abs(a), abs(b)), abs_tol)
isclose(a,b)
Error:
TypeError: unsupported operand type(s) for -: 'list' and 'list'
I tried to compare the two float lists in python but got the error. if matched otherwise show unmatched. Can anyone help me and provide me with an alternative way to do it.
CodePudding user response:
You have lists of strings - not floats. The method you use operates on numbers, not strings.
There is (for floats) an existing method to compare floats: math.isclose
If you want to compare lists you need to iterate the list. If you want to check floats, you need to convert to float before checking:
# use what already exists
from math import isclose
a = ['0.0','123.34','42']
b = ['0.0','123.34','3.141']
r = []
# same length lists, use zip to iterate pairwise, use enumerate for index
for idx, (aa, bb) in enumerate(zip(a,b)):
# convert to floats
aaa = float(aa)
bbb = float(bb)
# append if not close
if not isclose(aaa,bbb):
r.append((idx, (aaa,bbb)))
# print results
for w in r:
print("On index {0} we have {1} != {2}".format(w[0],*w[1]), sep="\n")
Output:
On index 2 we have 42.0 != 3.141
CodePudding user response:
You cannot use the '-' operator with lists. The code abs(a-b)
is first trying to do a-b
which it cannot do as a
and b
are lists.
You can write a function to subtract each index in list b
from each corresponding index in list a
and place the result of each computation in a new list with the same index.
Alternatively use numpy's numpy.subtract()
method to carry out this computation.
Furtheremore, abs()
cannot be used on a list object, you can write your own code that iterates over each element in a list and calculates the absolute value of each element or use numpy's numpy.absolute()
.
CodePudding user response:
With python you can't substract list object from each other. Moreover, you can't substract str object from each other.
You can do it with oneline :
a=['0.0','123.34'] #list
b=['0.0','123.34']
def isclose(a, b, rel_tol=1e-09, abs_tol=0.0):
return all([True if abs(float(i)-float(j)) <= max(rel_tol * max(abs(a), abs(b)), abs_tol) else False for i,j in zip(a,b) ])
isclose(a,b)
return True if both elements of lists are close
Greetings