user1692517
user1692517

Reputation: 1152

Filter from list - Python

I was wondering if someone can help me with a homework problem.

Write a function, func(a,x), that takes an array, a, x being both numbers, and returns an array containing only the values of a that are greater than or equal to x

I have

def threshold(a,x):
    for i in a:
        if i>x: print i

But this is the wrong method as I'm not returning it as an array. Can someone hint me the right direction. Thanks a lot in advance

Upvotes: 0

Views: 317

Answers (5)

The Internet
The Internet

Reputation: 8123

I think the homework problem is to actually implement a filter function. Not just use the built in one.

def custom_filter(a,x):
    result = []
    for i in a:
        if i >= x:
            result.append(i)
    return result

Upvotes: 0

Curious
Curious

Reputation: 2981

def threshold(a,x):
    vals = []
    for i in a:
        if i >= x: vals.append(i)
    return vals

Upvotes: 2

ovgolovin
ovgolovin

Reputation: 13430

Use list comprehensions:

[i for i in a if i>x]

Upvotes: 7

unutbu
unutbu

Reputation: 880917

You could use a list comprehension:

def threshold(a, x):
    return [i for i in a if i > x]

Upvotes: 4

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 251176

use the in-built function filter():

In [59]: lis=[1,2,3,4,5,6,7]
In [61]: filter(lambda x:x>=3,lis)  #return only those values which are >=3
Out[61]: [3, 4, 5, 6, 7]

Upvotes: 6

Related Questions