Programming/python

파이썬 any(), all() 기능은 무엇인가?

방황하는 데이터불도저 2023. 7. 15. 23:42

any(), all() 함수는 파이썬에서 제공하는 기본 내장함수로 
배열 형태를 가지는 iterable 변수인 리스트, 튜플 등이 boolean 원소를 가질 때,
any()는 True가 하나라도 있을 때, True를 반환하고
all()은 모든 원소가 True일 때, True를 반환하는 기능을 한다.
 
예를 들어, 아래와 같은 boolean을 원소로 가지는 리스트가 있다고 해보자.

l1 = [True, False, True]

이때, any(), all()함수는 아래와 같은 결과를 출력한다.

any(l1)      # return True
all(l1)      # return False

 
False인 경우는 0이나 " "와 같은 빈 값같은 경우가 될 수 있고, 그 이외의 숫자에는 True가 출력된다.

l2 = [0, False, '', 42]
any(l2)     # return True
all(l2)     # return False

 
숫자나 boolean값 이외에도 다양한 변수에 대한 배열에 함수를 응용하여 사용할 수 있다.

numbers = [5, 10, 0, -3]

# Check if any number is positive
if any(num > 0 for num in numbers):
    print("At least one number is positive")

# Check if all numbers are positive
if all(num > 0 for num in numbers):
    print("All numbers are positive")
def is_valid_email(email):
    # Custom email validation logic
    return '@' in email

def is_valid_password(password):
    # Custom password validation logic
    return len(password) >= 8

def validate_registration(email, password):
    validations = [
        is_valid_email(email),
        is_valid_password(password),
    ]

    if all(validations):
        print("Registration successful!")
    else:
        print("Invalid registration details.")

validate_registration("example@example.com", "password123")
usernames = ["john", "jane", "jim", "admin"]
has_long_username = any(len(username) > 8 for username in usernames)
print(has_long_username)  # Output: False

all_active_users = all(user.is_active for user in users)
print(all_active_users)  # Output: True