Development Tip

목록의 모든 값이 특정 숫자보다 큰지 확인

yourdevel 2020. 12. 15. 19:50
반응형

목록의 모든 값이 특정 숫자보다 큰지 확인


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

목록의 모든 값이> = 30인지 확인하는 방법은 무엇입니까? my_list1작동해야하고 작동 my_list2하지 않아야합니다.

내가 생각할 수있는 유일한 것은 :

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

2016 업데이트 :

돌이켜 보면 속도가 실제로 중요한 더 큰 데이터 세트를 처리하고 활용 한 후에 numpy...

>>> 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

다음과 같이 할 수도 있습니다.

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

생성기 표현식과 함께 all()함수사용하십시오 .

>>> 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

이 테스트는 30 보다 크 거나 같 으며 그렇지 않으면 my_list1테스트를 통과하지 못합니다.

함수에서이 작업을 수행하려면 다음을 사용합니다.

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

예를 들면 바로이 있다는 것을 증명하는 값 찾기로 (30) 아래의 값이 반환 하고, 반환 이 반대 증거를 찾을 수없는 경우입니다.FalseTrue

마찬가지로 any()함수사용하여 하나 이상의 값이 조건과 일치 하는지 테스트 할 수 있습니다 .


... 사용할 수없는 이유가 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

이것이 정확히 당신이 원하는 것인지 모르겠지만 기술적으로 이것은 당신이 요청한 것입니다 ...


내장 기능이 있습니다 all.

all (x > limit for x in my_list)

모든 숫자보다 더 큰 값을 제한합니다.


다음을 사용할 수 있습니다 all().

my_list1 = [30,34,56]
my_list2 = [29,500,43]
if all(i >= 30 for i in my_list1):
    print 'yes'
if all(i >= 30 for i in my_list2):
    print 'no'

여기에는 30 이상이 아닌 30 이상인 모든 숫자가 포함됩니다.


np.sum, np.min을 사용하는 것 사이의 전반적인 승자는 대형 배열의 속도 측면에서 np.min 인 것 같습니다.

N = 1000000
def func_sum(x):
    my_list = np.random.randn(N)
    return np.sum(my_list < x )==0

def func_min(x):
    my_list = np.random.randn(N)
    return np.min(my_list) >= x

def func_all(x):
    my_list = np.random.randn(N)
    return all(i >= x for i in my_list)

(i need to put the np.array definition inside the function, otherwise the np.min function remembers the value and does not do the computation again when testing for speed with timeit)

The performance of "all" depends very much on when the first element that does not satisfy the criteria is found, the np.sum needs to do a bit of operations, the np.min is the lightest in terms of computations in the general case.

When the criteria is almost immediately met and the all loop exits fast, the all function is winning just slightly over np.min:

>>> %timeit func_sum(10)
10 loops, best of 3: 36.1 ms per loop

>>> %timeit func_min(10)
10 loops, best of 3: 35.1 ms per loop

>>> %timeit func_all(10)
10 loops, best of 3: 35 ms per loop

But when "all" needs to go through all the points, it is definitely much worse, and the np.min wins:

>>> %timeit func_sum(-10)
10 loops, best of 3: 36.2 ms per loop

>>> %timeit func_min(-10)
10 loops, best of 3: 35.2 ms per loop

>>> %timeit func_all(-10)
10 loops, best of 3: 230 ms per loop

But using

np.sum(my_list<x)

can be very useful is one wants to know how many values are below x.


You could do the following:

def Lists():

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

    for element in my_list1:
        print(element >= 30)

    for element in my_list2:
        print(element >= 30)

Lists()

This will return the values that are greater than 30 as True, and the values that are smaller as false.


I write this function

def larger(x, than=0):
    if not x or min(x) > than:
        return True
    return False

Then

print larger([5, 6, 7], than=5)  # False
print larger([6, 7, 8], than=5)  # True
print larger([], than=5)  # True
print larger([6, 7, 8, None], than=5)  # False


Empty list on min() will raise ValueError. So I added if not x in condition.

ReferenceURL : https://stackoverflow.com/questions/20229822/check-if-all-values-in-list-are-greater-than-a-certain-number

반응형