Python:替代“if”条件列表

我正在寻找在更少的代码行中使用多个“if”条件的更优雅的替代方案。大多数条件都非常简单,如示例所示:

        if status == 'young':
            i = 1
        elif status == 'middle age':
            i = 3
        elif status == 'elder':
            i = 4
        elif status == 'baby':
            i = 5
        elif status == 'deceased':
            i = 6

我想做一些类似的事情:

if status == 'young', 'mid age', 'elder'...
   i = 1, 3, 4...

在python中可以吗??

回答

使用字典

statuses = {'young': 1, 'middle age': 3}
i = statuses.get(status)

  • And if you need to simulate an `else`, the second argument to `.get` is the default to return if the key is not in the dictionary.

以上是Python:替代“if”条件列表的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>