Python中C型Switch语句实现的混乱

2024-09-30 18:12:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图使用dictionary在Python中实现switch语句,但我遇到了一个问题。你知道吗

下面是我正在尝试的:

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

输出:

输入i的值

1个

20个

但我预计10岁输出。所以呢,这里的主要问题是,它正在为i==1&;i==2执行这两个语句。另外,我不能在这里使用break。你知道吗

那么如何获得期望的输出呢?你知道吗


Tags: oftruehelloinputrawdictionaryreturnvalue
3条回答

我想你的开关应该是:

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)都被调用

编辑添加默认案例,因为有人关心这个问题。你知道吗

我把行动和逻辑分开,像这样:

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)

你把自己搞复杂了吗?如果只是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'()

会成功的

相关问题 更多 >