python - 在设置的情况下,每个开关情况都在工作
问题描述
我正在尝试在 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 结束
解决方案
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。
推荐阅读
- python-3.x - 如何使用用户输入打印语句?
- html - 如何在侧容器中的元素之间添加边距而不推送到下一行
- java - 是否可以从 Python 运行 java 以创建 .png?
- c# - 在 xaml 中使用键绑定捕获一系列字符
- .htaccess - 如何使用 .htaccess 将所有 .eu 页面重定向到 .nl?
- ios - 为一个或另一个扩展具有多个约束的协议 - Swift
- ios - CMSampleBufferGetImageBuffer(sampleBuffer) 返回 nil
- merge - 在 Keras 中通过卷积合并两个张量
- vba - countifs 标准范围大于 vba
- javascript - 如何在剑道网格 UI 中显示总和 groupFooterTemplate