Python:为什么比较 int 与字符串的相等性不会引发错误? [英] Python: Why does equality comparing an int with a string not throw an error?
问题描述
在 Python 3 中,尝试对字符串和 int 进行排序(例如 1 > "1"
)会引发 TypeError.为什么将字符串与 int 进行比较不会引发错误?(例如 1=="1"
)将字符串与 int 进行比较有意义的示例是什么?为什么 JavaScript 和 SQL 采用不同的方法?
In Python 3 the attempt to order a string and an int (e.g. 1 > "1"
) throws a TypeError.
Why does comparing a string with an int for equality not throw an error? (e.g. 1=="1"
)
What is an example where comparing a string with an int makes sense?
Why do JavaScript and SQL take a different approach?
推荐答案
例如,这允许您拥有一个包含混合类型键的字典.
This allows you, for example, to have a dictionary with keys of mixed types.
如果您无法比较 1
和 "1"
是否相等,您将无法将它们用作同一字典中的键.
If you couldn't compare 1
and "1"
for equality, you wouldn't be able to use them as keys into the same dictionary.
就目前情况而言,您可以比较它们,它们总是比较不平等:
As things stand, you can compare them, and they always compare unequal:
对象不必具有相同的类型.如果两者都是数字,则将它们转换为公共类型.否则,不同类型的对象总是比较不相等,并且顺序一致但随意.
The objects need not have the same type. If both are numbers, they are converted to a common type. Otherwise, objects of different types always compare unequal, and are ordered consistently but arbitrarily.
这篇关于Python:为什么比较 int 与字符串的相等性不会引发错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!