Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
456 views
in Technique[技术] by (71.8m points)

python - Check if all values in list are greater than a certain number

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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Use the all() function with a generator expression:

>>> my_list1 = [30, 34, 56]
>>> my_list2 = [29, 500, 43]
>>> all(i >= 30 for i in my_list1)
True
>>> all(i >= 30 for i in my_list2)
False

Note that this tests for greater than or equal to 30, otherwise my_list1 would not pass the test either.

If you wanted to do this in a function, you'd use:

def all_30_or_up(ls):
    for i in ls:
        if i < 30:
            return False
    return True

e.g. as soon as you find a value that proves that there is a value below 30, you return False, and return True if you found no evidence to the contrary.

Similarly, you can use the any() function to test if at least 1 value matches the condition.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...