Suppose I have the following lists:
x = [0.5, 0.9, 0.1, 0.3, 0.6]
y = [0.4, 0.3, 0.6, 0.1, 0.9]
I want to write a function that iterates through the list and compares each value in order.
JavaScriptx91def compare_numbers(prob,thresh):
2output = []
3for x, y in zip(prob, thresh):
4if x >= y:
5output.append(1)
6else:
7output.append(0)
8return output
9
JavaScript121compare_numbers(x,y)
2
This gives me Type Error: 'float' object is not iterable'
Why is this?
I would expect the output to look like this:
[1, 1, 0, 1, 0]
Is there anyway I could write this function such that if the “threshold” value was only one digit it would still work?
My current code to make the latter function is:
JavaScript191def compare_numbers(prob, thresh):
2output = []
3for n in prob:
4if n >= thresh:
5output.append(1)
6else:
7output.append(0)
8return output
9
JavaScript121compare_numbers(x,y)
2
Yet this returns the Type Error: TypeError: '>=' not supported between instances of 'int' and 'list'
when thresh is a list.
Advertisement
Answer
The problem is that you are comparing the value n from prob with the entire list thresh. What you need to do is to also iterate over thresh. Here is a small fix that will allow your code to work:
def compare_numbers(prob, thresh):
output = []
for n in range(len(prob)):
if prob[n] >= thresh[n]:
output.append(1)
else:
output.append(0)
return output