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.
def compare_numbers(prob,thresh): output = [] for x, y in zip(prob, thresh): if x >= y: output.append(1) else: output.append(0) return output
compare_numbers(x,y)
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:
def compare_numbers(prob, thresh): output = [] for n in prob: if n >= thresh: output.append(1) else: output.append(0) return output
compare_numbers(x,y)
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