
[英]Check if all values of a list are less than a certain number, if not set it to that number
[英]Check if all values in a list are bigger than certain number x and smaller than y?
def fun_lst(lst, a, b):
if min(lst)<b and max(lst)>a:
return True
return False
如何检查列表中的值是否大于a
且小于b
? 我尝试了上面的方法,但在此示例中: fun_lst([-1, 3.5, 6], -2.4, 0)
该函数返回True
,并且应该返回False
。
def fun_lst(lst, a, b):
if min(lst) > a and max(lst) < b:
return True
return False
print(fun_lst([-1, 3.5, 6], -2.4, 0) )
输出:
False
min(lst) > a
可确保每个元素比更大 。 max(lst) < b
确保每个元素都小于 b。 def fun_lst(lst, a, b):
return all(a < elem < b for elem in lst)
如果您愿意,可以尝试使用这款内胆
all([num < b and num > a for num in lst])
此处的代码将检查列表中的每个项目,如果找到一个不大于a且小于b的项目,则返回false,否则返回true。
def fun_lst(lst, a, b):
for item in lst:
if not a < item < b:
return False
return True
myList = [1,2,3,4,5,6,7,8,9]
lower_limit = 3
upper_limit = 8
bool_output = all([i > lower_limit and i < upper_limit for i in myList])
print(bool_output)
False
myList = [1,2,3,4,5,6,7,8,9]
lower_limit = 0
upper_limit = 10
bool_output = all([i > lower_limit and i < upper_limit for i in myList])
print(bool_output)
True
您应该尝试这样:
def fun_lst(lst, a, b):
return all(n > a and n < b for n in lst)
如果您有使用numpy
的规定,请尝试以下操作
In [1]: import numpy as np
In [3]: np.array(b)
Out[3]: array([ 3, 1, 4, 66, 8, 3, 4, 56])
In [17]: b[(2<b) & (b<5)]
Out[17]: array([3, 4, 3, 4])
不同的方法:
def fun_lst(lis, x, y):
list = [i>x and i<y for i in lis]
return False if False in list else True
这有点简单:
def fun_lst(lis, x, y):
return x<max(lis)<y
lambda版本:
fun_lst = lambda lis, x, y: x<max(lis)<y
输出:
fun_lst([-1, 3.5, 6], -2.4, 0) #Output: False
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.