从列表中过滤 - Python

时间:2012-09-23 18:18:49

标签: python arrays list filter

我想知道是否有人可以帮我解决作业问题。

写一个函数func(a,x),它接受一个数组,a,x是两个数字,并返回一个只包含大于或等于x的值的数组

我有

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

但这是错误的方法,因为我没有将它作为数组返回。有人能暗示我正确的方向。非常感谢提前

5 个答案:

答案 0 :(得分:7)

使用list comprehensions

[i for i in a if i>x]

答案 1 :(得分:6)

使用内置函数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]

答案 2 :(得分:4)

您可以使用list comprehension

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

答案 3 :(得分:2)

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

答案 4 :(得分:0)

我认为功课问题是实际实现过滤功能。不只是使用内置的。

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