>>> "Monty" < "Python"
True
>>> "Z" < "a"
True
>>> "Monty" < "Montague"
False
这有什么规矩?是字母的数量还是什么?谢谢
>>> "Monty" < "Python"
True
>>> "Z" < "a"
True
>>> "Monty" < "Montague"
False
这有什么规矩?是字母的数量还是什么?谢谢
它是按字典顺序排序的。所以“a”<“b”。
如果您使用该ord()
函数,您可以看到“Z”的值低于“a”
>>> ord('Z')
90
>>> ord('a')
97
Python 字符串、元组和列表使用Lexicographical order进行比较。
元组示例:
>>> (1,2) < (2,1)
True
>>> (1,2) < (1,2,-5)
True
想法很简单:逐个元素比较(对于字符串,逐个字符),直到有差异或一个更短。
Be careful not to confuse this order with the locale sensitive collation sequence. For example:
>>> import locale
>>> locale.strcoll("Z","a")
-1
>>> "Z" < "a"
True
Probably what you expect, locale.strcoll
returns -1 if the first string is less than the second, +1 if the first string is greater than the second (0 if they are equal).
But:
>>> locale.setlocale(locale.LC_ALL,"")
'English_United Kingdom.1252'
>>> locale.strcoll("Z","a")
1
>>> "Z" < "a"
True
The locale can change the collation sequence, but (here) not with ordinary comparisons. The English collation sequence goes aAbBcC...xXyYzZ (applies to other "en" locales). For example:
>>> ml=["a","b","c","A","B","C"]
>>> sorted(ml)
['A', 'B', 'C', 'a', 'b', 'c']
>>> sorted(ml,key=locale.strxfrm)
['a', 'A', 'b', 'B', 'c', 'C']
>>>
With non-ASCII characters, consider:
>>> locale.strcoll("é","f")
-1
>>> "é" < "f"
False
按照字母在 ASCII 范围内定义的顺序进行词法排序,因此:
A ... Za ... z
这就是为什么'Z' < 'a'
是真的。
比较两个字符串时,比较每个字符,如果一个大于另一个,则字符串更大,如果相等,则移动到下一个字符。如果到达其中一个字符串的末尾,而另一个字符串仍然有字符,则最长的字符串更大,否则它们相等。