반응형
케이스/스위치 스테이트먼트에 대응하는 Python은 무엇입니까?
하는 Python이 ?switch
★★★★★★★★★★★★?
Python 3.10 이후
Python 3.10에서는 패턴 매칭을 도입했습니다.
Python 문서의 예:
def http_error(status):
match status:
case 400:
return "Bad request"
case 404:
return "Not found"
case 418:
return "I'm a teapot"
# If an exact match is not confirmed, this last case will be used if provided
case _:
return "Something's wrong with the internet"
Python 3.10 이전 버전
공식 문서에서는 다음을 제공하지 않지만switch
, 나는 사전을 이용한 해결책을 본 적이 있다.
예를 들어 다음과 같습니다.
# define the function blocks
def zero():
print "You typed zero.\n"
def sqr():
print "n is a perfect square\n"
def even():
print "n is an even number\n"
def prime():
print "n is a prime number\n"
# map the inputs to the function blocks
options = {0 : zero,
1 : sqr,
4 : sqr,
9 : sqr,
2 : even,
3 : prime,
5 : prime,
7 : prime,
}
입니다.switch
블록이 호출됩니다.
options[num]()
만약 당신이 실패에 크게 의존한다면, 이것은 무너지기 시작한다.
는 「」입니다.if
/elif
/else
그러나 많은 경우 Python에서 더 나은 방법을 사용할 수 있습니다."Python의 스위치 문에 대한 대체?"를 참조하십시오.
언급URL : https://stackoverflow.com/questions/11479816/what-is-the-python-equivalent-for-a-case-switch-statement
반응형
'programing' 카테고리의 다른 글
지속적인 편집으로 주문 데이터 무결성 유지 (0) | 2022.11.05 |
---|---|
MySQL이 여러 문자를 대체할 수 있습니까? (0) | 2022.11.05 |
MySQL 함수는 두 날짜 사이의 근무 일수를 구합니다. (0) | 2022.11.05 |
mysqldump 출력을 작은 파일로 분할하려면 어떻게 해야 합니까? (0) | 2022.11.05 |
객체의 키를 찾으려면 어떻게 해야 합니까? (0) | 2022.11.05 |