1

我想编写一个返回大于或等于的数组值的函数x

这是我的代码:

def threshold(a,x): 
    b = a[x:]
    return b

如果xis3ais [1,2,3,4,5],函数将返回[3,4,5]

** 忘了提到这些值可能没有排序。输入可以是 [1,3,2,5,4],如果 x 为 3 则必须返回 [3,4,5] **

4

4 回答 4

5

使用生成器表达式和sorted

>>> def threshold(a, x):
...     return sorted(item for item in a if item >= x)
... 
>>> threshold([1,3,2,5,4], 3)
[3, 4, 5]
于 2013-09-20T15:05:36.127 回答
2

使用内置函数filter是另一种方法:

def threshold(a, x):
    return filter(lambda e: e>= x, a)

>>> threshold([1, 3, 5, 2, 8, 4], 4)
[5, 8, 4]
于 2013-09-20T15:16:40.643 回答
1

这是另一个版本

threshold = (lambda a, x :filter(lambda element: element >= x, a))
于 2013-09-20T15:16:17.027 回答
0

您可能需要考虑numpy

import numpy as np
a = np.array([1,2,3,4,5])
a[a>2]

array([3,4,5])
于 2013-09-20T16:00:38.337 回答