python - 奇怪的python比较行为

标签 python compare

我有一个如下所示的示例代码,值(position = 2,object.position = 3):

    new_position = position
    old_position = object.position    

    logging.debug("1. new_position: %s, old_position: %s" % (new_position, old_position))

    if old_position != new_position:
        logging.debug("old position other than new position")
        if new_position > old_position:
            logging.debug("Why am I here ?")

现在是调试:

DEBUG 1. new_position: 2, old_position: 3
DEBUG 2. old position other than new position
DEBUG Why am I here?

最佳答案

这可能是因为您正在比较不同的不兼容类型(例如字符串和整数)。如果是这样,则顺序取决于类型名称的字母顺序。

>>> '2' > 3
True

这适用于 Python 2.x。在 Python 3.x 中,这将引发 TypeError

关于python - 奇怪的python比较行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4060066/

相关文章:

Java字符串数组: how do I check if the array has a value?

python - Selenium Page down by ActionChains

python - 每分钟更新一次 QWidget

python - 将 Python itertools 组合移至文件

python - 如何在 Python 中比较对象的类型?

matlab - 在另一个向量 matlab 中查找向量的一部分

.net - 字符串不等于字符串?

python - 如何获取 numpy/scipy 中特定百分位数的索引?

python - 在导入的 __init__.py 中导入行为不同

php - 如何从按时间戳过滤的数据库中选择结果?