Reputation: 310
I have a list and I have a constant, and I want to know which elements in the list is greater than a constant.
ls = [2, 1, 0, 1, 3, 2, 1, 2, 1]
constant = 1.5
So I simply did:
ls >= constant
I expect it to return:
[TRUE, FALSE, FALSE, FALSE, TRUE, TRUE, FALSE, TRUE, FALSE]
But it returned an error!!!
TypeError Traceback (most recent call last)
<ipython-input-92-91099ebca512> in <module>
----> 1 ls > constant
TypeError: '>' not supported between instances of 'list' and 'float'
How to python compare a vector to a simple constant value?
Upvotes: 0
Views: 685
Reputation: 71434
The most Pythonic (IMO) way to get the list you describe is with a list comprehension:
>>> [n >= constant for n in ls]
[True, False, False, False, True, True, False, True, False]
It's almost the same as what you wrote, but you want to do the comparison on each individual n
value for n in ls
, rather than on ls
itself.
If you want the actual values, that's a very similar expression:
>>> [n for n in ls if n >= constant]
[2, 3, 2, 2]
In this case, the actual value in the list is n
, but we only include it at all if n >= constant
.
Upvotes: 1
Reputation: 5746
You can use a list comprehension to assess values whilst looping.
You need to loop when comparing elements as you cannot compare a list
to an integer
.
output = [x > constant for x in ls]
#[True, False, False, False, True, True, False, True, False]
Upvotes: 5
Reputation: 2007
You can use map()
for this and lambda functions.
print(list(map(lambda n:n>=constant, ls)))
The reason your code doesn't work is that a list and float cannot be compared. In order for comparisons to work, they need to be of the same object (or the magic methods be pre-defined to work with custom objects).
Upvotes: 1