본문 바로가기

파이썬

[파이썬] any()와 List Comprehension

any()

help(any)

>>any(iterable, /)
      Return True if bool(x) is True for any x in the iterable.
    
      If the iterable is empty, return False.

 

파이썬 명령어 중 any()는 내부에 iterable 객체를 받으면(리스트나 튜플 등)

객체 중 하나라도 True 면 True를 반환하는 함수 

 

def has_lucky_number(nums):
    """Return whether the given list of numbers is lucky. A lucky list contains
    at least one number divisible by 7.
    7로 나누어 떨어지는 수를 포함하는 리스트가 들어오면 True 반환하기
    """
    for num in nums:
        if num % 7 == 0:
            return True
    # We've exhausted the list without finding a lucky number
    #리스트내 객체를 다 돌았는데도 7로 나누어떨어지는 수가 없음.
    return False

#List Comprehension으로 한줄로 쓰기
def has_lucky_number(nums):
	"""nums 리스트 내의 객체 num을 for문으로 접근해서 7로 나누어 떨어지는 수가 하나라도 있을 경우
	any()를 사용해서 True가 나오게 됨. 7의 배수가 없을 경우 자동 False
	"""
    return any([num % 7 == 0 for num in nums])

 

리스트 컴프리헨션 잘 쓰면 너무 좋다. 대신 연습이 많이 필요함. 

 

 

참고: kaggle-Learn Tutorial Python - loops and list comprehensions

https://www.kaggle.com/code/colinmorris/loops-and-list-comprehensions

 

Loops and List Comprehensions

Explore and run machine learning code with Kaggle Notebooks | Using data from No attached data sources

www.kaggle.com