在 Python 中切换 [英] Switch in Python
问题描述
我尝试在 python 中创建一个类似 switch 的语句,而不是有很多 if 语句.
I have tried making a switch like statement in python, instead of having a lot of if statements.
代码如下:
def findStuff(cds):
L=[]
c=0
for i in range(0, len(cds), 3):
a=differencesTo(cds[i:i+3])
result = {
a[2][0]==1: c=i+1,
a[2][1]==1: c=i+2,
a[2][2]==1: c=i+3,
a[1]==1: L.append((cds[i:i+3], a[0], c))
}
return L
我的问题是,这不起作用.(适用于 if 语句,但在我看来这会更漂亮).
My problem is, that this does not work. (Works with if statements, but this would in my opinion be more pretty).
我在 Python 中找到了一些开关示例,它们都遵循这种结构.有人可以帮我吗?
I have found some examples of switches in Python, and they follow this structure. Can anyone help me?
推荐答案
(a) 我看不出 if...elif...else 有什么问题
(a) I fail to see what is wrong with if...elif...else
(b) 我假设 python 没有 switch 语句,原因与 Smalltalk 没有的相同:它几乎完全是多余的,如果你想打开类型,你可以添加一个适当的方法你的课;同样,打开值应该在很大程度上是多余的.
(b) I assume that python does not have a switch statement for the same reason that Smalltalk doesn't: it's almost completely redundant, and in the case where you want to switch on types, you can add an appropriate method to your classes; and likewise switching on values should be largely redundant.
注意:我在评论中获悉,无论 Guido 最初没有创建 switch 的原因是什么,添加它的 PEP 都被拒绝了,因为支持添加这样的声明是极其有限.请参阅:http://www.python.org/dev/peps/pep-3103/
Note: I am informed in the comments that whatever Guido's reason for not creating a switch in the first place, PEPs to have it added were rejected on the basis that support for adding such a statement is extremely limited. See: http://www.python.org/dev/peps/pep-3103/
(c) 如果您确实需要切换行为,请使用哈希表 (dict
) 来存储可调用对象.结构为:
(c) If you really need switching behaviour, use a hashtable (dict
) to store callables. The structure is:
switch_dict = {
Foo: self.doFoo,
Bar: self.doBar,
}
func = switch_dict[switch_var]
result = func() # or if they take args, pass args
这篇关于在 Python 中切换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!