python—如何编写一个函数,在数字位于某个范围内时对其进行过滤

sshcrbum  于 2021-09-08  发布在  Java
关注(0)|答案(1)|浏览(167)

我想写一个函数 inRange ,它将返回一个列表,其中包含 l 其值介于低值和高值之间(包括低值和高值)。例如 inRange(3, 10, [2, 3, 7, 17, 10, 7, -9]) 返回 [3, 7, 10, 7] . 我只能使用map、filter、reduce、list、lambda来完成这个函数。
这是我当前无法使用的代码:

def inRange(lo, hi, l):
    return list(filter(lambda lo, hi, l: l in range(lo, hi))

print(inRange(10, 20, [10, 14, 16, 17, 20, 21, 23, 12]))````
1tu0hz3e

1tu0hz3e1#

您正在寻找此功能:

def inRange(lo, hi, l):
     return list(filter(lambda i: lo <= i <= hi, l))

print(inRange(10, 20, [10, 14, 16, 17, 20, 21, 23, 12]))

输出:

[10, 14, 16, 17, 20, 12]

参考:
python中的filter()

相关问题