본문으로 건너뛰기

내가 주로 사용하는 Python 문법(20.12.20 기준)

· 약 1분
Seokjae Lee
Software engineer

원문: https://doljae.tistory.com/6

변수 관련​

# 한 줄에 변수를 2개 이상 선언할 수 있다
a, b = 10, 20
# 자료구조도 마찬가지
c, d = [], []

# *args 문법
board = [1, 2, 3, 4, 5]
a, *b, c = board
# a=1, b=[2,3,4], c=5

<!-- truncate -->

# swap
a, b = 5, 10
a, b = b, a
# a=10, b=5

list 조작 1​

# map
board = [1, 2, 3, 4, 5]
new_board = list(map(lambda x: x * 2, board))
# new_board = [2,4,6,8,10]

# filter
board = [1, 2, 3, 4, 5]
new_board = list(filter(lambda x: x > 2, board))
# new_board = [3,4,5]

# 복잡한 조건을 넣어야 할 경우 따로 함수를 선언해 사용
board = [1, 2, 3, 4, 5]

def mapping_function(input_value):
if input_value % 2 == 0:
return "짝"
else:
return "홀"

new_board = list(map(lambda x: mapping_function(x), board))
# new_board = ["홀","짝","홀","짝","홀"]

list 조작 2​

# extend
list1 = [1, 2, 3]
list2 = [4, 5, 6]
list3 = list1 + list2
# list3=[1,2,3,4,5,6]

# slicing
list4 = list1[:2] + list2
# list4=[1,2,4,5,6]

# minus indexing
temp = list1[-1] + list2[-1]
# temp=9