VB.NET や C# で利用可能な例など、case ステートメントに相当する Python はありますか?
1772567 次
2 に答える
742
Python 3.10 以降
Python 3.10 では、パターン マッチングが導入されました。
def http_error(status):
match status:
case 400:
return "Bad request"
case 404:
return "Not found"
case 418:
return "I'm a teapot"
case _:
return "Something's wrong with the internet"
Python 3.10 より前
公式ドキュメントでは switch が提供されていないことを喜んでいますが、dictionaries を使用した解決策を見てきました。
例えば:
# 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]()
フォールスルーに大きく依存している場合、これは崩壊し始めます。
于 2012-07-14T00:05:45.890 に答える
231
直接置換はif
/ elif
/else
です。
ただし、多くの場合、Python でそれを行うためのより良い方法があります。「 Python での switch ステートメントの置換は? 」を参照してください。
于 2012-07-14T10:39:09.650 に答える