python - 为什么 '362' > 378?

标签 python string comparison integer

<分区>

Possible Duplicate:
How does Python compare string and int?

一位实习生要求我帮助调试看起来像这样的代码:

widths = [image.width for image in images]
widths.append(374)
width = max(widths)

...当第一行应该是:

widths = [int(image.width) for image in images]

因此,代码选择的是字符串“364”而不是整数 374。python 究竟如何比较字符串和整数?我可以理解将单个字符(如果 python 具有 char 数据类型)与整数进行比较,但我没有看到任何直接的方法来将字符串与整数进行比较。

最佳答案

Python 2.x 将每个 内置类型与其他每个类型进行比较。来自docs :

Objects of different types, except different numeric types and different string types, never compare equal; such objects are ordered consistently but arbitrarily (so that sorting a heterogeneous array yields a consistent result).

CPython 中的这种“任意顺序”实际上是按类型名排序的。

在 Python 3.x 中,如果您尝试将字符串与整数进行比较,您将得到一个 TypeError

关于python - 为什么 '362' > 378?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6259623/

相关文章:

python - 新消息到达时终止先前的高速公路 websocket 调用

java - 将字符串拆分为一个值

java - 以编程方式在 TextView 中设置文本的正确方法

javascript - jQuery 或 javascript 可以从文本字符串中确定日期,然后比较两个日期吗?

python - 导致 AttributeError 的多个词典?

python - 如何使用 .explore() 显示 geopandas 交互式 map

python - 根据用户请求或超时后停止正则表达式搜索

C# 在另一个函数中覆盖 string 和 string[]

javascript - 如果 ([] == false) 为真,为什么 ([] || true) 结果为 []?

c++ - 在 C++ 中是否有可移植的指针关系比较的替代方法?