Becker
Becker 의 TIL
Becker
  • 분류 전체보기 (30)
    • Computer Science (15)
      • Python (7)
      • Java (1)
      • Algorithm (0)
      • Database (3)
      • Network (1)
      • Openstack (2)
      • ETC (1)
    • 자동화 (3)
      • Github Action (1)
      • Airflow (0)
      • Docker (2)
    • 논문 리뷰 (1)
    • 서평 (3)
    • 끄적끄적 (8)
전체 방문자
오늘
어제

인기 글

티스토리

hELLO · Designed By 정상우.
Becker

Becker 의 TIL

[Pythonic Code] 파이썬스러운 코드!
Computer Science/Python

[Pythonic Code] 파이썬스러운 코드!

2022. 12. 27. 11:31

https://www.renatocandido.org/2020/10/7-python-code-examples-for-everyday-use/

Pythonic code?

  • 파이썬의 기능을 최대한 살려서 코드를 짜는 것!
  • 읽기 편하고 유지보수를 쉽게하는 클린코드!
  • 좋은 가독성과 코드 일관성을 유지할 수 있다!

list comprehension

  • 파이썬스럽게 list를 생성하는 방법
  • 가장 많이 사용되는 기법중 하나
  • for + append 보다 빠른속도로 리스트를 생성할 수 있다

Unpythonic

result =[]
for i in range(0,10):
	result.append(i)

Pythonic

result = [i for i in range(10)]
result = [i for i in range(10) if i % 2 == 0]

 

✅ append와 속도 비교를 비교해보면 실행 성능 차이를 확실히 알 수 있다!

 


split & join

  • split : String type을 기준값으로 나눠서 list로 반환
  • join : String으로 구성된 list를 합처 하나의 string으로 반환
#split
items = 'zero one two three'.split() # 빈칸 기준 문자열 나누기
example = 'python,java,javascript'.split(',') # 쉼표(,) 기준 문자열 나누기

print("items ", items)
print('example', example)

unpack = 'team,ai,deeplearning'
team, ai, deeplearning = unpack.split(',')
print(team, ai, deeplearning)
colors = ['red','blue','green','yellow']
result = ' '.join(colors) # red blue green yellow

enumerate & zip

  • enumerate : list의 element를 추출할 때 index를 붙여서 추출
  • zip : 두개의 list의 값을 병렬적으로 추출
#enumerate example

#example 1
tic_tac_toe = ['tic', 'tac', 'toe']

for index, value in enumerate(tic_tac_toe):
  print(index, value)

# 0 tic
# 1 tac
# 2 toe

#example 2
my_list = ['a', 'b', 'c', 'd']
print(list(enumerate(my_list)))

#[(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd')]

#example 3
#abcd = ['a', .... 'g']
dic = {i:j for i, j in enumerate("The Quick Brown Fox Jumps Over The Lazy Dog".split())}
print(dic)

#{0: 'The', 1: 'Quick', 2: 'Brown', 3: 'Fox', 4: 'Jumps', 5: 'Over', 6: 'The', 7: 'Lazy', 8: 'Dog'}
#zip
a_list = ['a1', 'a2', 'a3']
b_list = ['b1', 'b2', 'b3']
for a, b in zip(a_list, b_list):
  print(a, b)

# a1 b1
# a2 b2
# a3 b3

c_list = ['c1', 'c2', 'c3', 'c4'] # 길이가 다르면?
for a, c in zip(a_list, c_list):
  print(a,c)

*Asterisk

  • 가변인자 -> 개수가 정해지지 않은 변수!
  • args : 함수에서 사용할 인자의 개수를 모를 때 사용!
  • *kwargs : 키워딩 된 가변인자({key : value} 형태)
  • 입력값은 tuple type로 사용할 수 있음
  • 함수 파라미터의 마지막에 위치
first, *second, third = ['one', 'two', 'three', 'four', 'five']
print(second)
# ['two', 'three', 'four']

 

  • 단순 곱셈, 제곱연산, 가변인자등에 사용
  • tuple, dict를 unpacking
def asterisk_test(a,b, *args):
  print(args)
  print(type(args)) # tuple
  return a + b + sum(args)

asterisk_test(1,2,3,4,5)

# (3, 4, 5)
# <class 'tuple'>

#----------------------------

print(1 * 2) # 2
print(2 ** 2) # 4

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

def unpack_asterisk(a, b, args):
  print(a, *args) # unpack
  print(a, args)  # packed tuple
  print(type(args))

unpack_asterisk(1,2, (3,4,5,6))

# 1 3 4 5 6
# 1 (3, 4, 5, 6)
# <class 'tuple'>
#unpack and zip
#실행 전 어떤 값이 출력될지 생각해보기
for data in zip(*([1,2],[3,4],[5,6])):
  print(data)
def kwargs_test_1(**kwargs):
  print(kwargs)

def kwargs_test_2(**kwargs):
  print("First value is {first}".format(**kwargs))
  print("Second value is {second}".format(**kwargs))
  print("Third value is {third}".format(**kwargs))

kwargs_test_1(a=1,b=2,c=3)

# {'a': 1, 'b': 2, 'c': 3}

kwargs_test_2(first = 1, second = 2, third = 3)

# First value is 1
# Second value is 2
# Third value is 3

실행 노트북

pythonic_code.ipynb

참고 자료

[Python] 파이썬스럽게 코드 쓰기, Pythonic Code

Pythonic Code - 파이썬 스타일 코드

 

 

'Computer Science > Python' 카테고리의 다른 글

[Python] FastAPI와 Dependency Injector  (3) 2024.10.27
[Python] 비동기 테스트를 하려면? (a.k.a pytest-asyncio)  (4) 2024.04.28
[Python] UoW(Unit of Work) 패턴을 알아보자  (0) 2024.04.14
[Python] SqlAlchemy 1.4 -> 2.0 마이그레이션 단계별 가이드  (1) 2024.03.31
[Python] Tox로 여러 환경에서 테스트하기  (1) 2023.07.02
    'Computer Science/Python' 카테고리의 다른 글
    • [Python] 비동기 테스트를 하려면? (a.k.a pytest-asyncio)
    • [Python] UoW(Unit of Work) 패턴을 알아보자
    • [Python] SqlAlchemy 1.4 -> 2.0 마이그레이션 단계별 가이드
    • [Python] Tox로 여러 환경에서 테스트하기
    Becker
    Becker

    티스토리툴바