【问题标题】:Ordering of string representations of integers [duplicate]整数的字符串表示的排序[重复]
【发布时间】: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


【解决方案1】:

您正在比较字符串而不是数字。

20 > 9 计算 True 的数值类型,如整数和浮点数,但使用 lexicographical 比较 (strings) 然后 '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'>

【讨论】:

    【解决方案2】:

    这是一个字典比较。一旦发现一个大于另一个的元素,比较就会停止,所以

    '5' > '15'
    

    为真,因为 '5' 大于 '1'

    【讨论】:

      【解决方案3】:

      答案是从最左边的字符开始比较字符串,或“字典顺序”。这给出了直观的结果,例如,

      "an" < "b" # True
      

      如果您想比较 字符串所代表的数字的值,您应该明确说明:

      int("15") < int("5") # False
      

      【讨论】:

        【解决方案4】:

        您正在比较字符串,因为您的数字被单引号括起来。

        在 python 中,应用于字符串的 运算符使用字典顺序比较它们。 您可以在 '5' 之前放置一个 '0' 进行测试:

        '05' > '11'
        

        【讨论】:

          【解决方案5】:

          它正在比较初始数字。就好像它是按字母顺序排列的一样。 5 &gt; 1 这就是为什么你会得到5 &gt; 16

          【讨论】:

            【解决方案6】:

            确实,字符'5'ascii 值大于'1' 的值,因此'5' &gt; '15' 的计算结果为True。由于字符串比较是逐字节进行的,就像字典中单词的长度不会影响它的位置'5' &gt; '1412423513515'也是True

            >>> '5' > '15'
            True
            >>> ord('5')
            53
            >>> ord('1')
            49
            

            想想像字母字符这样的整数的字符串表示,即'z' &gt; 'abc' 的计算结果为True,因为'z''a' 之后。这称为lexicographic ordering

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2012-04-16
              • 2014-07-31
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多