简体   繁体   English

为什么 'aa' < 'z' 在 Python 中的计算结果为 True?

[英]Why does 'aa' < 'z' evaluate to True in Python?

I am working with string comparison in Python.我正在使用 Python 进行字符串比较。 Why does 'aa' < 'z' evaluate to True.为什么'aa' < 'z'评估为 True。 Further, why does 'aa' < 'a' evaluate to False.此外,为什么'aa' < 'a'评估为 False。 I tried explaining 'aa' is of a longer length than 'a' so it would be greater.我试着解释 'aa' 的长度比 'a' 长,所以它会更大。 But this reasoning does not work for the initial case 'aa' < 'z'但是这种推理不适用于初始情况 'aa' < 'z'

'aa' < 'z' => True 'aa' < 'a' => False 'aa' < 'z' => True 'aa' < 'a' => False

String comparisons use lexicographical order.字符串比较使用字典顺序。 To put it in simple terms, it's the order in which words would appear in a dictionary.简单来说,就是单词在字典中出现的顺序。 Your examples would look like this:您的示例如下所示:

a
aa
z

And clearly 'a' < 'aa' is True as well as 'aa' < 'z' .显然'a' < 'aa'True以及'aa' < 'z' If two words consist of the same character repeated several times, the shortest word would go first.如果两个单词由多次重复的相同字符组成,则最短的单词将排在第一位。 For the rest, it's just the order of the alphabet.其余的,这只是字母表的顺序。

They're in dictionary order.它们按字典顺序排列。 Alphabetical order first, length as a tie breaker.按字母顺序排列,长度作为决胜局。 Just like in a dictionary, a precedes aa which precedes z .就像在字典中一样, aaa之前,在z之前。

I think, you can help the function ord() to understand it.我想,你可以帮助函数 ord() 理解它。 https://www.programiz.com/python-programming/methods/built-in/ord https://www.programiz.com/python-programming/methods/built-in/ord

If see your example 'aa' < 'a' => False first symbol from 'aa' have an integer representing the Unicode character 97 and result 97 < 97 => False .如果看到您的示例 'aa' < 'a' => False 来自 'aa' 的第一个符号有一个整数表示 Unicode 字符97和结果97 < 97 => False If we see next your example 'aa' < 'z' => True.如果我们接下来看到您的示例 'aa' < 'z' => True。 Python see only first symbol like this 'a' < 'z' == 97 < 122 => True . Python 只看到像这样第一个符号'a' < 'z' == 97 < 122 => True

I hope I can help you!我希望我能帮助你!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM