简体   繁体   English

从列表中过滤-Python

[英]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 编写一个函数func(a,x),该函数接受一个数组,a,x是两个数字,然后返回一个仅包含大于或等于x的a的值的数组

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 提前谢谢

使用清单理解

[i for i in a if i>x]

use the in-built function filter() : 使用内置函数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]

You could use a list comprehension : 您可以使用列表推导

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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