230524_TIL(Today_I_Learned)

신진철·2023년 5월 24일
0

TIL

목록 보기
3/3

TIL (Today I Learned) 날짜
2023-05-24(수)

오늘 TIL 3줄 요약

  • Loops
  • List comprehensions
  • 적은 코드로 문제를 해결하는 것도 좋지만 클린 코드(가독성)

공부한 내용 쓰기

Loops(반복문)

  • for
    - 사용할 변수 이름
    - 반복할 값 세트
    - in이라는 단어를 사용하여 서로 연결(예시1)
    - List 외에도 tuple의 요소를 반복 할 수 있다(예시2)
    - 문자열의 각 문자를 반복할 수 있다(예시3)
    - range()
    - 일련의 숫자를 반환하는 함수
    - 루프 작성에 매우 유용
# 예시1 - List[]
planets = ['Mercury', 'Venus', 'Earth', 'Mars', 'Jupiter', 'Saturn', 'Uranus', 'Neptune']
for planet in planets:
    print(planet, end=' ') # print all on same line

# 예시2 - tuple()
multiplicands = (2, 2, 2, 3, 3, 5)
product = 1
for mult in multiplicands:
    product = product * mult
product

# 예시3 - isupper()
s = 'steganograpHy is the practicE of conceaLing a file, message, image, or video within another fiLe, message, image, Or video.'
msg = ''
# print all the uppercase letters in s, one at a time
for char in s:
    if char.isupper():
        print(char, end='')

# 예시4 - range() 작업을 5번 반복하기
for i in range(5):
    print(i)
  • while
    - 조건이 충족될 때까지 반복(예시1)
# 예시1
i = 0
while i < 10:
    print(i, end=' ')
    i += 1 # increase the value of i by 1
  • List comprehensions
    - 한줄 반복문(예시1)
    - if문을 추가 할 수 있다(예시2)
    - if 조건으로 필터링하고 일부 변환을 루프 변수에 적용할 수 있다(예시3)
    - SQL의 WHERE절과 비슷
    - 사람들은 일반적으로 한 줄에 작성하지만 세 줄로 나눌 때 구조가 더 명확하다(예시4)
    - SQL 비유를 계속하면 이 세 줄을 SELECT, FROM 및 WHERE와 비슷
    - min, max 및 sum과 같은 함수와 결합된 목록 내포는 여러 줄의 코드가 필요한 문제에 대해 인상적인 한 줄 솔루션으로 이어질 수 있다.(예시5)
    - 더 적은 코드로 문제를 해결하는 것도 좋지만 The Zen of Python를 명심하자
    - 다른 사람들이 이해하기 쉬운 코드가 좋다
    	가독성이 중요합니다.
    	 명시적인 것이 암시적인 것보다 낫습니다.
# 예시1 List comprehensions
squares = [n**2 for n in range(10)] # 제곱 List 문

# 예시1 기본문
squares = []
for n in range(10):
    squares.append(n**2)

# 예시2 if문 추가
short_planets = [planet for planet in planets if len(planet) < 6]

# 예시3
# str.upper() returns an all-caps version of a string
loud_short_planets = [planet.upper() + '!' for planet in planets if len(planet) < 6]

# 예시4 - 예시3의 세줄화
[
    planet.upper() + '!' 
    for planet in planets 
    if len(planet) < 6
]

# 예시5
def count_negatives(nums):
    """Return the number of negative numbers in the given list.
    >>> count_negatives([5, -1, -2, 0, 3])
    2
    """
    n_negative = 0
    for num in nums:
        if num < 0:
            n_negative = n_negative + 1
    return n_negative

# 예시5 한줄화
def count_negatives(nums):
    return len([num for num in nums if num < 0])

# 예시5 다른 한줄화 
def count_negatives(nums):
    # Reminder: in the "booleans and conditionals" exercises, we learned about a quirk of 
    # Python where it calculates something like True + True + False + True to be equal to 3.
    return sum([num < 0 for num in nums])

오늘 공부한 소감은?

  • Kaggle 튜토리얼이 정리가 생각보다 잘되어 있어 공부하며 정리하기 너무 좋다
  • List comprehensions은 더 잘 활용하기 위해 노력해야겠다

궁금한 내용이 있거나, 잘 이해되지 않는 내용이 있다면?

  • List comprehensions 아직 완벽히 이해하지 못했다

출처

profile
열심히 성장하겠습니다

0개의 댓글