这是我今天遇到的另一个巨大陷阱.
我花了几个小时调试我的代码,最后我发现它是由这个奇怪的设置引起的
下面是我的python提示界面
'3' > '2'
True
'4' > '3'
True
'15' > '11'
True
'999233' > '123'
True
# At this point, you must think compare string numbers is just like compare numbers.
# Me too, but...
'5' > '15'
True
# What's this !!!???
# Meanwhile I am asking this question. I want to something exaggerated to mockerying
# this mechanism, and I find something surprised me:
'5' > '999233'
False
# What!!!???
# Suddenly an idea come across my mind, are they comparing the first string number
# at first, if they are equal and then compare the second one?
# So I tried:
'5' > '13333333333333333'
True
'5' > '61'
False
# That's it.
# my old doubt disappeared and a new question raised:
Run Code Online (Sandbox Code Playgroud)
他们为什么设计这样的机制而不是使用自然数比较机制?在"字符串数字"比较中使用此机制有什么好处?
你正在比较字符串而不是数字.
20 > 9计算True数字类型,如整数和浮点数,但使用词典比较(字符串)然后'20' < '9'计算True
例:
$ python
>>> 5 > 10
False
>>> '5' > '10'
True
>>> '05' > '10'
False
>>> 'abc05' > 'bca10'
False
>>> 'dog' > 'cat'
True
>>> type('10')
<type 'str'>
>>> type(10)
<type 'int'>
Run Code Online (Sandbox Code Playgroud)