[머신러닝을 위한 파이썬] Pythonic Code

2024. 12. 22. 12:19MOOC

1. Split 함수

  • 문자열을 특정 기준으로 나누어 리스트 형태로 변환하는 함수.
  • 기본적으로 공백을 기준으로 나누며, 원하는 기준을 직접 설정 가능.
  • unpacking으로 리스트의 요소를 변수에 직접 할당 가능.
items = 'zero one two three'.split()  # 공백 기준
print(items)  # ['zero', 'one', 'two', 'three']

example = 'python,jquery,javascript'
print(example.split(','))  # [ 'python', 'jquery', 'javascript' ]

a, b, c = example.split(",")  # unpacking

2. Join 함수

  • 리스트에 담긴 문자열 요소들을 하나의 문자열로 합칠 때 사용.
  • 구분자를 설정하여 각 요소 사이에 삽입 가능.
colors = ['red', 'blue', 'green']
print(''.join(colors))  # 'redbluegreen'
print(', '.join(colors))  # 'red, blue, green'

3. List Comprehension

  • 기존 리스트를 기반으로 간단하게 새로운 리스트를 생성하는 기법.
  • 코드가 간결해지고, 속도도 for + append 방식보다 빠름.
result = [i for i in range(10)]  # 0~9까지의 숫자
result = [i for i in range(10) if i % 2 == 0]  # 짝수만

 

중첩 루프 예제

word_1, word_2 = "Hello", "World"
result = [i+j for i in word_1 for j in word_2]
print(result)  # ['HW', 'Ho', 'Hr', ..., 'od']

4. zip 함수

  • 여러 리스트를 묶어서 동시에 순회하거나, 요소를 결합하는 데 사용.
alist = ['a1', 'a2', 'a3']
blist = ['b1', 'b2', 'b3']
for a, b in zip(alist, blist):
    print(a, b)
# a1 b1
# a2 b2
# a3 b3

 

리스트 압축과 zip

a, b, c = zip((1, 2, 3), (10, 20, 30), (100, 200, 300))
print(a, b, c)  # (1, 10, 100), (2, 20, 200), (3, 30, 300)

print([sum(x) for x in zip((1, 2), (10, 20), (100, 200))])  # [111, 222]

5. Lambda와 Map/Reduce

Lambda (익명 함수)

  • 한 줄로 함수를 간단히 정의.
  • 함수 이름이 필요 없을 때 유용.
f = lambda x, y: x + y
print(f(1, 4))  # 5

print((lambda x: x**2)(3))  # 9

Map

  • 시퀀스의 각 요소에 동일한 함수를 적용.
  • 여러 리스트를 동시에 처리 가능.
ex = [1, 2, 3, 4, 5]
print(list(map(lambda x: x**2, ex)))  # [1, 4, 9, 16, 25]

Reduce

  • 리스트 요소를 누적하여 하나의 값으로 합침.
  • functools.reduce를 사용해야 함.
from functools import reduce
print(reduce(lambda x, y: x + y, [1, 2, 3, 4, 5]))  # 15

6. Asterisk(*) 활용

  • 다양한 파라미터 처리 방식에 사용.

Packing

def test(a, *args):
    print(a, args)
test(1, 2, 3, 4)  # 1 (2, 3, 4)

 

Unpacking

data = ([1, 2], [3, 4], [5, 6])
print(*data)  # [1, 2] [3, 4] [5, 6]

 

Dictionary Unpacking

def test(a, b, c):
    print(a, b, c)
data = {"a": 1, "b": 2, "c": 3}
test(**data)  # 1 2 3