Matt Walker
Matt Walker

Reputation: 181

Return array values that are greater than x

I would like to write a function that returns array values that are greater than or equal to x

Here is my code :

def threshold(a,x): 
    b = a[x:]
    return b

If x is 3, and a is [1,2,3,4,5], the function would return [3,4,5]

** Forgot to mention that the values might not be sorted. Input could be [1,3,2,5,4], and it would have to return [3,4,5] if x is 3 **

Upvotes: 1

Views: 1562

Answers (4)

Lee
Lee

Reputation: 31050

You might want to consider numpy:

import numpy as np
a = np.array([1,2,3,4,5])
a[a>2]

gives

array([3,4,5])

Upvotes: 1

falsetru
falsetru

Reputation: 369134

Using generator expression and sorted:

>>> def threshold(a, x):
...     return sorted(item for item in a if item >= x)
... 
>>> threshold([1,3,2,5,4], 3)
[3, 4, 5]

Upvotes: 5

Leon Young
Leon Young

Reputation: 585

Using built-in function filter is an alternative way:

def threshold(a, x):
    return filter(lambda e: e>= x, a)

>>> threshold([1, 3, 5, 2, 8, 4], 4)
[5, 8, 4]

Upvotes: 2

llazzaro
llazzaro

Reputation: 4188

Here is another version

threshold = (lambda a, x :filter(lambda element: element >= x, a))

Upvotes: 1

Related Questions