首页 > 解决方案 > 在设置的情况下,每个开关情况都在工作

问题描述

我正在尝试在 python 中使用 switch case 从集合中删除元素,但问题是 switch h 的每个 case 都在运行

我在 python 3 中试过这个

if __name__ == '__main__':
    s = set([1,2,3,4,6,5])
    d = 5


    switcher = {'pop':s.pop(),
                'remove':s.remove(5),
                'discard':s.discard(4)}
    switcher.get('remove', 'nothing')
    print(s)

{2, 3, 6}

进程以退出代码 0 结束

标签: pythonpython-3.xlistswitch-statementset

解决方案


Python 没有switch声明。那是一个字典。set([])语法也已过时。改为使用{}

s = {1,2,3,4,6,5}

如果要延迟对表达式的评估,可以使用lambda.

switcher = {'pop': lambda: s.pop(),
            'remove': lambda: s.remove(5),
            'discard': lambda: s.discard(4)}
switcher.get('remove', 'nothing')()

当您确实想要评估它时,不要忘记调用它。

但是有一种更常见的方法来制作带有名称的函数的字典:一个类。

if __name__ == '__main__':
    s = {1,2,3,4,6,5}
    class Switcher:
        def pop():
            s.pop()
        def remove():
            s.remove(5)
        def discard():
            s.discard(4)
    Switcher.remove()
    print(s)

请注意,这些“方法”没有self参数,因此您不需要实例。它只是一个包含函数的结构,例如 lambda dict。


推荐阅读