240620 TIL #430 Pythonic Code

김춘복·2024년 6월 19일
0

TIL : Today I Learned

목록 보기
430/494

Today I Learned

오늘 공부한 내용은 파이썬 스타일의 코딩 방법이다.


Pythonic Code

Split & Join

  • split() : string 타입의 값을 기준값으로 나눠서 list형태로 변환하는 함수
# sep은 구분자로 미지정시 공백 기준. maxsplit은 문자열을 나눌 최대 횟수로 미지정시 전체 나눔
str.split(sep=None, maxsplit=-1)

csv_line = "apple,banana,cherry"
fruits = csv_line.split(',')  # 콤마를 기준으로 나눔
print(fruits)  # ['apple', 'banana', 'cherry']
  • join() : join은 리스트나 튜플같은 iterable을 하나로 합침
sep.join(iterable)

words = ['Python', 'is', 'fun']
sentence = ' '.join(words)  # 공백을 구분자로 리스트 요소들을 결합
print(sentence)  # 'Python is fun'

fruits = ['apple', 'banana', 'cherry']
csv_line = ','.join(fruits)  # 콤마를 구분자로 리스트 요소들을 결합
print(csv_line)  # 'apple,banana,cherry'

리스트 컴프리헨션

파이썬에서 반복문과 조건문을 사용해 리스트를 생성하는 간결한 방법

[표현식 for 항목 in iterable if 조건]

numbers = [1, 2, 3, 4, 5]
evens = [n for n in numbers if n % 2 == 0]
print(evens)  # [2, 4]

# 2차원 평탄화 시 사용
matrix = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
]
flat = [num for row in matrix for num in row]
print(flat)  # [1, 2, 3, 4, 5, 6, 7, 8, 9]


enumerate & zip

  • enumerate : 리스트에서 반복문 사용시 인덱스를 같이 추출해줌
fruits = ['apple', 'banana', 'cherry']

for index, fruit in enumerate(fruits):
    print(index, fruit)
# 0 apple
# 1 banana
# 2 cherry

# 인덱스를 1부터 시작
for index, fruit in enumerate(fruits, start=1):
    print(index, fruit)
# 1 apple
# 2 banana
# 3 cherry
  • zip : 두 개 이상의 iterable을 병렬로 순회
names = ['Alice', 'Bob']
ages = [25, 30, 35]

for name, age in zip(names, ages):
    print(f"{name} is {age} years old.")
# 출력:
# Alice is 25 years old.
# Bob is 30 years old.

# 함께 사용시
names = ['Alice', 'Bob', 'Charlie']
ages = [25, 30, 35]
cities = ['New York', 'Los Angeles', 'Chicago']

for index, (name, age, city) in enumerate(zip(names, ages, cities)):
    print(f"{index}: {name} is {age} years old and lives in {city}.")
# 출력:
# 0: Alice is 25 years old and lives in New York.
# 1: Bob is 30 years old and lives in Los Angeles.
# 2: Charlie is 35 years old and lives in Chicago.

profile
꾸준히 성장하기 위해 매일 log를 남깁니다!

0개의 댓글