2012-09-23 59 views
0

我在想,如果有人能幫助我有家庭作業的問題。過濾器 - Python的

寫功能,FUNC(A,X),即帶有一個數組,A,X爲兩個數字,並返回包含僅是大於或等於x

我的的一個值的數組有

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

但這是錯誤的方法,因爲我沒有將它作爲數組返回。有人可以暗示我正確的方向嗎?非常感謝提前

回答

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] 
+0

謝謝!只是我正在尋找的方法。 我仍然不明白lambda的用法,所以我現在就去閱讀它。 – user1692517

+0

@ user1692517上'lambda'是好的,但我更喜歡列表理解在這種情況下閱讀了,這也很容易理解。 – jamylak

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

我認爲功課題實際上是實現了一個過濾功能。不只是使用內置的一個。

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