[Python] 파이썬의 match-case

FeelingXD·2023년 8월 12일
2

python

목록 보기
1/7
post-thumbnail

Python 3.10.0 에 추가된 match case 기능에대해 간단하게 정리한 글 입니다.

Match-case

😀
python 3.10.0 버전 이전에는 다른 언어의 switch-case 분기문이 없었다. 과거 python 문서에서도 switch case 처럼 사용하고자한다면 딕셔너리나 if-elif 구조를 권장했다. python 3.10.0 으로 업그레이드 됨에따라 추가적으로 다른 언어의 switch-case 처럼 분기문인 match-case 문법이 추가되었다. 이 글에서는 이에 대해 작성한다.

// java , c 언어 등에서의 switch case 표기법
switch(입력변수) {
    case 입력값1: ...
         break;
    case 입력값2: ...
         break;
    ...
    default: ...
         break;
}
# ex 1
# 간단하게 예제를 보자 [1,2,3] 를 원소를 가지는 case 를 순회하며 원소에대해 검사하여 각각의 케이스에대해 분기에대해 다른 출력문을 실행한다.

case = [1, 2, 3]

for i in case:
    match i:
        case 1:
            print(f'this 1')
        case 2:
            print(f'this 2')
        case 3:
            print(f'this 3')

기본적으로 match-case 의 패턴검사는 from top to bottom(위에서 아래) 으로 의 방식으로 분기문을 탐색한다.
python match-case 의 재미있는점은 다른 언어 에서의 switch case 문처럼 case 마다 break 을 따로 작성해주지 않아도 되며.
가장 처음 match 되는 case를 실행시킨다.

2. guard

python 의 match-case 에 조건을 걸어 case문 패턴과 같이 검사에 이용할수 있다.
파이썬에서는 이를 가드라고 표현한다.

heros = ["batman", "robin"]
villains = ["joker"]
ext = ["엑스트라1", "엑스트라2"]
for p in heros+villains+ext:
    match p:
        case x if x in heros:
            print(f'{x} is a hero')
        case x if x in villains:
            print(f'{x} is a villain')
        case x:
            print(f'{x} who are you ?')

3.wild card

다른 언어에서 아무케이스에 일치하지않는경우 기본적으로 실행할 default를 실행 할수있는데 python 의 match-case 에서는 다음과 같이 사용할수있다.

pos = 5, 10
pos2 = 1, 10
test = [pos, pos2]

for t in test:
    match t:
        case (5, y):
            print(f"this case 5,{y}")
        case x:
            print(f"wild card used input {x}")

제일 마지막 case x: 의 경우가 이에 해당 한다. 모든 경우에서 print(f"wild card used input {x}") 실행한다. (top to bottom으로 조건을 발견하지 못할시)

profile
tistory로 이사갑니다. :) https://feelingxd.tistory.com/

0개의 댓글