【发布时间】:2014-04-21 13:57:20
【问题描述】:
这是我今天遇到的另一个巨大陷阱。
我花了几个小时调试我的代码,最后我发现它是由这个奇怪的设置引起的
下面是我的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:
为什么他们设计了这样的机制而不是使用自然数比较机制? 在“字符串编号”比较中使用这种机制有什么好处?
【问题讨论】:
-
谷歌词典比较
-
你认为这些数字周围的
'是什么意思? -
我认为这不足为奇。如果字符串比较根据被比较字符串的内容以不同的方式工作,那将是令人惊讶的。字符串是字符串;在这种情况下,它们恰好由可以解释为十进制数的数字序列组成,这并不重要。
-
@T.J.Crowder ,这迫使它们成为字符串。我对它们进行的测试让我相信它们的顺序一开始就像正常数字一样。
-
@Mario:是的,它们是字符串,而不是数字,这就是它们被比较的方式。
'5' > '3'的原因与'e' > 'a'相同。'5' > '15'的原因与'e' > 'ae'相同。
标签: python