AME*_*AME 25 python syntax switch-statement
我试图用8位二进制字符串检查每个索引.如果它是'0'那么'OFF'否则它'ON'.
是否有更简洁的方法来编写具有类似开关功能的代码.?
Sov*_*iut 32
不,不.说到语言本身,Python的核心原则之一就是只有一种方法可以做某事.该交换机是多余的:
if x == 1:
pass
elif x == 5:
pass
elif x == 10:
pass
Run Code Online (Sandbox Code Playgroud)
(当然没有掉头).
该开关最初是作为C的编译器优化引入的.现代编译器不再需要这些提示来优化这种逻辑语句.
Jef*_*eff 11
试试这个:
def on_function(*args, **kwargs):
# do something
def off_function(*args, **kwargs):
# do something
function_dict = { '0' : off_function, '1' : on_function }
for ch in binary_string:
function_dict[ch]()
Run Code Online (Sandbox Code Playgroud)
或者,如果函数返回值,则可以使用列表推导或生成器表达式:
result_list = [function_dict[ch]() for ch in binary_string]
Run Code Online (Sandbox Code Playgroud)
从 Python 3.10.0 (2021 年 3 月 30 日发布的 alpha6)开始,现在有一个官方的真正的语法等效项!
digit = 5
match digit:
case 5:
print("The number is five, state is ON")
case 1:
print("The number is one, state is ON")
case 0:
print("The number is zero, state is OFF")
case _:
print("The value is unknown")
Run Code Online (Sandbox Code Playgroud)
我已经写了另一个 Stack Overflow 答案,其中我尝试涵盖您可能需要了解或关注的所有内容match。
| 归档时间: |
|
| 查看次数: |
42706 次 |
| 最近记录: |