python中string和int的内部比较 [英] internal comparison of string and int in python

查看:39
本文介绍了python中string和int的内部比较的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当一个字符串和一个整数比较时,string和int在内部是和ASCII码比较的,还是怎么做的?我知道字符串比较大于整数,但内部比较是如何进行的?

<预><代码>>>>一个">1真的

解决方案

在您的示例中,1 <"a" 因为 int 的 "i" 按字母顺序排在 string 的 "s" 之前.

来自文档:

<块引用>

不同类型的对象,除了不同的数字类型和不同的字符串类型,永远不要比较相等;这样的对象是有序的一致但任意(以便对异构数组进行排序产生一致的结果).

我相信这是在 python 3 中改变的事情之一(你会在这里得到一个 TypeError).

<小时>

至于在CPython中是怎么做的,除数字外的不同类型的对象都是按类型名排序的;不支持正确比较的相同类型的对象按其地址排序.请注意,这是实现的一部分,而不是语言的一部分.

When a string is being compared to an integer are the string and int compared with the ASCII code internally, or how is it? I know that strings compare greater than integers, but how does that internal comparison takes place?

>>> "a" > 1
True

解决方案

In your example, 1 < "a" because "i" for int comes alphabetically before "s" for string.

From the 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).

I believe this was one of the things changed in python 3 (you would get a TypeError here).


As for how it is done in CPython, objects of different types except numbers are ordered by their type names; objects of the same types that don’t support proper comparison are ordered by their address. Note that this is part of the implementation, not a part of the language.

这篇关于python中string和int的内部比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆