【问题标题】:How to do switch case in python depending on 4 variables如何根据 4 个变量在 python 中切换大小写
【发布时间】:2020-09-17 17:29:46
【问题描述】:

我正在尝试根据 4 个输入变量的值从我创建的 16 个字典中选择一个。

我认为可以通过 switch 完成,但到目前为止我还没有得到它。

我认为“逻辑”可能与此类似:

variable_1 = 0
variable_2 = 1
variable_3 = 1
variable_4 = 0



def func_select_dict(variable_1, variable_2, variable_3, variable_4)

        switch(0,0,0,0):
                final_dictionary = dictionary_1

        switch(0,0,0,1):
                final_dictionary = dictionary_2

        switch(0,0,1,0):
                final_dictionary = dictionary_3

        ...............

        switch(1,1,1,1):
                final_dictionary = dictionary_16

有什么想法吗?

【问题讨论】:

标签: python conditional-statements


【解决方案1】:

例如,如果您将字典放在列表中

>>> dicts = [{'dict': i} for i in range(16)]
>>> dicts
[{'dict': 0}, {'dict': 1}, {'dict': 2}, {'dict': 3}, {'dict': 4}, {'dict': 5}, {'dict': 6}, {'dict': 7}, {'dict': 8}, {'dict': 9}, {'dict': 10}, {'dict': 11}, {'dict': 12}, {'dict': 13}, {'dict': 14}, {'dict': 15}]

您可以使用一些巧妙的位移来根据您的变量索引到该列表中

def to_index(v1, v2, v3, v4):
    return v1 << 3 | v2 << 2 | v3 << 1 | v4

例如

>>> to_index(0, 1, 1, 0)
6
>>> dicts[to_index(0, 1, 1, 0)]
{'dict': 6}

您当前的方法将不起作用,因为 Python 没有 switch 语句,即使它规范地这样做也只能用于整数类型,而不是元组。

【讨论】:

  • 谢谢,这正是我所需要的!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-09-26
相关资源
最近更新 更多