Joe*_*ith 2 python dictionary switch-statement
我正在尝试在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”)
Run Code Online (Sandbox Code Playgroud)
它返回:
Traceback (most recent call last):
File "/Gower71/Switch.py", line 5, in <module>
switchDict[str(type(varX))]()
KeyError: "<class ‘float'>"
Run Code Online (Sandbox Code Playgroud)
如果我将switchDict行更改为:
switchDict = {bool: "boolean", int: "integer", float: "floatType", str: "string"}
switchDict[type(varX)]()
Run Code Online (Sandbox Code Playgroud)
它返回:
Traceback (most recent call last):
File "/Gower71/Switch.py", line 5, in <module>
switchDict[type(varX)]()
TypeError: 'str' object is not callable
Run Code Online (Sandbox Code Playgroud)
有没有办法打开这样的类型?
您应该将实际的函数引用存储为值,而不是将它们的名称存储为字符串.示例 -
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)]()
Run Code Online (Sandbox Code Playgroud)
为此,您需要在定义所有函数后移动字典的构造.
此外,建议不要使用string作为函数的名称,它与string标准模块的冲突.最好使用其他名称,如string_type左右.