Check if all values in list are greater than a cer

2019-01-22 01:13发布

my_list1 = [30,34,56]
my_list2 = [29,500,43]

How to I check if all values in list are >= 30? my_list1 should work and my_list2 should not.

The only thing I could think of doing was:

boolean = 0
def func(ls):
    for k in ls:
        if k >= 30:
            boolean = boolean + 1
        else:
            boolean = 0
    if boolean > 0:
        print 'Continue'
    elif boolean = 0:
        pass

Update 2016:

In hindsight, after dealing with bigger datasets where speed actually matters and utilizing numpy...I would do this:

>>> my_list1 = [30,34,56]
>>> my_list2 = [29,500,43]

>>> import numpy as np
>>> A_1 = np.array(my_list1)
>>> A_2 = np.array(my_list2)

>>> A_1 >= 30
array([ True,  True,  True], dtype=bool)
>>> A_2 >= 30
array([False,  True,  True], dtype=bool)

>>> ((A_1 >= 30).sum() == A_1.size).astype(np.int)
1
>>> ((A_2 >= 30).sum() == A_2.size).astype(np.int)
0

You could also do something like:

len([*filter(lambda x: x >= 30, my_list1)]) > 0

7条回答
手持菜刀,她持情操
2楼-- · 2019-01-22 02:02

...any reason why you can't use min()?

def above(my_list, minimum):
    if min(my_list) >= minimum:
        print "All values are equal or above", minimum
    else:
        print "Not all values are equal or above", minimum

I don't know if this is exactly what you want, but technically, this is what you asked for...

查看更多
登录 后发表回答