简体   繁体   English

在Python中实现C类型Switch语句时的困惑

[英]Confusion in implementation of C type Switch statement in Python

I am trying to implement switch statement in Python by using dictionary ,but i am getting one problem in that. 我试图通过使用字典在Python中实现switch语句,但我遇到了一个问题。

Below is what i am trying: 以下是我正在尝试的内容:

print "Enter value of i"
i=eval(raw_input())

j=0
def switch(i):
    print "Hello\n"
    return {True: 'gauw',
            i==1: a(10),
            i==2: a(20),
            }[True]
def a(t):
    global j
    j=t
switch(i)
print j

Output: 输出:

Enter value of i 输入i的值

1 1

20 20

But i am expecting 10 as output.So,here the main problem is that,it is executing both statement for i==1 & i==2 . 但我期待10作为输出。所以,这里的主要问题是,它正在执行i==1i==2两个语句。 Also,I can't use break here. 另外,我不能在这里使用break

So how to get desired output? 那么如何获得理想的输出呢?

Y do you complicate yourself? 你让自己变得复杂吗? If its just the implementation of switch, use if and elif. 如果它只是执行switch,请使用if和elif。

def switch(i):
    if i==1:
        a(10)
    elif i==2: #Even if here wil work, instead of elif
        a(20)
    else:
        return 'gauw'()

Will do the trick 会做的伎俩

I think your switch should be: 我认为你的开关应该是:

print "Enter value of i"
i=eval(raw_input())

j=0
def switch(i):
    print "Hello\n"
    try:
        return {
                1: a,
                2: b,
                }[i]()
    except:
        // default action here
        return 'gauw'
def a():
    global j
    j=10
def b():
    global j
    j=20
switch(i)
print j

a(10), a(20) are both invoked when the dictionary was built a(10),a(20)都是在构建字典时调用的

EDIT Adding a default case since there are people who cares about this. 编辑添加默认案例,因为有人关心这个。

I'd separate actions from logic, something like this: 我将动作与逻辑分开,如下所示:

action_dict = dict([
    (1, lambda: a(10)),
    (2, lambda: a(20)),
    ])

def switch(value, actions):
    if value in actions:
        return actions[value]()
    return 'gauw'

print "Enter value of i"
i=eval(raw_input())

switch(i, action_dict)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM