我正在尝试用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”)
它返回:
^{pr2}$
如果我将switchDict行更改为:switchDict = {bool: "boolean", int: "integer", float: "floatType", str: "string"}
switchDict[type(varX)]()
它返回:Traceback (most recent call last):
File "/Gower71/Switch.py", line 5, in
switchDict[type(varX)]()
TypeError: 'str' object is not callable
有没有办法打开这样的字体??在