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
'파이썬' 카테고리의 다른 글
[판다스] 시리즈 만드는 법: 리스트 이용해서 간단하게 (0) | 2024.01.20 |
---|---|
[판다스] 데이터프레임을 만드는 다양한 방법과 컬럼명 지정하기 (0) | 2024.01.20 |
[판다스] pandas.set_option error 옛 코드를 돌리다가 오류 났을 때 (0) | 2024.01.20 |
[파이썬] 키워드를 리스트 안에서 검색하기 (0) | 2024.01.17 |
[파이썬] 불리언 연산 순서 (0) | 2024.01.16 |