我想知道是否有人可以帮我解决作业问题。
写一个函数func(a,x),它接受一个数组,a,x是两个数字,并返回一个只包含大于或等于x的值的数组
我有
def threshold(a,x):
for i in a:
if i>x: print i
但这是错误的方法,因为我没有将它作为数组返回。有人能暗示我正确的方向。非常感谢提前
答案 0 :(得分:7)
[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