简体   繁体   中英

Find first element in list where value is greater than a constant

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?

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]

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).

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM