在数据类型上对 "switch" 使用 python 字典

Use a python dictionary for "switch" on datatype

我正在尝试在 python 中编写一个“switch”字典。我希望能够从文本文件中读取数据,并根据它的数据类型做不同的事情。因此,例如,如果我读入一个字符串,我想将它与另一个字符串进行比较。或者,如果我读取一个浮点数,我想用它做一些操作。这是机器学习程序的数据清理操作。

我可能可以使用 If...Else 语句来做到这一点,但由于可以想象我可以为每种数据类型提供一些东西,所以我宁愿把它做​​得更干净。

我正在使用以下代码:

varX = 2.0
switchDict = {"bool": "boolean", "int": "integer","float": "floatType",
               "str": "string"}

switchDict[str(type(varX))]()

def boolean():
    print("You have a boolean" )

def integer():
    print("You have an integer")

def floatType():
    print("You have a float")

def string():
    print("You have a string”)

它returns:

Traceback (most recent call last):
  File "/Gower71/Switch.py", line 5, in <module>
switchDict[str(type(varX))]()
KeyError: "<class ‘float'>"

如果我将 switchDict 行更改为:

switchDict = {bool: "boolean", int: "integer", float: "floatType", str: "string"}
switchDict[type(varX)]()

它returns:

Traceback (most recent call last):
  File "/Gower71/Switch.py", line 5, in <module>
    switchDict[type(varX)]()
TypeError: 'str' object is not callable

有没有办法像这样打开类型??

您应该将实际函数引用存储为值,而不是将它们的名称存储为字符串。示例 -

def boolean():
    print("You have a boolean" )

def integer():
    print("You have an integer")

def floatType():
    print("You have a float")

def string():
    print("You have a string")

switchDict = {bool: boolean, int: integer, float: floatType, str: string}
switchDict[type(varX)]()

为此,您需要将字典的构造移动到定义所有函数之后。

此外,建议不要使用string作为函数名,它与标准模块string冲突。最好使用其他名称,例如 string_type 左右。