python中不同类型的变量的比较

时间:2017-05-23 08:37:27

标签: python

在我的脚本中,我从2个不同的数据库得到2个变量Val1和Val2,我必须比较它们。

问题是,如果变量的类型不同,变量可能在数据库中表示相同的含义。

所以'' (空字符串或字符串仅包含空格)表示与0或0或无

相同

我是否必须检查变量类型的所有可能组合? 我该怎么做才能确保不会遗漏某个类型?

def CompareValues(Val1,Val2,Debug=False):

    if Val1 is None and Val2 is float:
        if Debug:print('none-float')
        if Val2 == 0.        : return True
    if Val1 is None and Val2 is int:
        if Debug:print('none-int')
        if Val2 == 0         : return True
    if Val1 is None and Val2 is str:
        if Debug:print('none-str')
        if Val2.strip() == '': return True
    [...]
    return False

它有更多的pythonic方式吗?

2 个答案:

答案 0 :(得分:0)

你可以做到

if not Val1:
    #True for [],{},'',0,0.0,False,None, etc..

对于类型检查,您应该isinstance

In [10]: isinstance(0.0, float)
Out[10]: True

In [11]: isinstance("mystring", str)
Out[11]: True

答案 1 :(得分:0)

编写一个接受'' ' ' '0'0并返回零的函数,换句话说,将您获得的数据强制转换为通用数据类型。

然后比较功能结果。

例如

def coerce(n):
    if type(n) is str:
        n = n.strip()
    if not n:
        return 0
    if type(n) is str and n.isdigit():
        return int(n.strip())
    return n

>>> coerce("")
0
>>> coerce("  ")
0
>>> coerce("0")
0
>>> coerce("4")
4
>>> coerce("") == coerce(0)
True