J. Smith J. Smith - 3 years ago 440
Python Question

TypeError: '<' not supported between instances of 'str' and 'float' when trying to change values

Im trying to write code that checks a list for a value < 0 and if there is one, replace it with 0. Whenever i write my if statement, i get the error in the title, I know its the fact im trying to compare i with 0 but i just cant figure out how to properly get this if statemtnt to work.

import random

for i in range(50):

float_cvalues=[float(i) for i in cvalues]
final_cvalues=["{0:.2f}".format(i) for i in float_cvalues]

nvalues=[.4*i-.8 for i in float_cvalues]
float_nvalues=[float(i) for i in nvalues]
nvalues_changed=["{0:.2f}".format(i)for i in nvalues]

for i in nvalues_changed:
if(i < 0):


Answer Source

It seems that your code is jumping between str and float. If you want to round your numbers to two decimal places, use round(), don't convert it to string.

Anyways, here's your code, although admittedly, shortened:

import random

float_cvalues = [round(float(random.randrange(0, 16)), 2) for _ in range(50)]
nvalues = [round(float(.4 * i - .8), 2) for i in float_cvalues]

changed_nvalues = [0 if i < 0 else i for i in nvalues]

test = list(zip(float_cvalues, changed_nvalues))

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download