How does tuple comparison work in Python?

前端 未结 4 1840
梦毁少年i
梦毁少年i 2020-11-22 04:26

I have been reading the Core Python programming book, and the author shows an example like:

(4, 5) < (3, 5) # Equals false

So,

4条回答
  •  闹比i
    闹比i (楼主)
    2020-11-22 05:09

    I had some confusion before regarding integer comparsion, so I will explain it to be more beginner friendly with an example

    a = ('A','B','C') # see it as the string "ABC" b = ('A','B','D')

    A is converted to its corresponding ASCII ord('A') #65 same for other elements

    So, >> a>b # True you can think of it as comparing between string (It is exactly, actually)

    the same thing goes for integers too.

    x = (1,2,2) # see it the string "123" y = (1,2,3) x > y # False

    because (1 is not greater than 1, move to the next, 2 is not greater than 2, move to the next 2 is less than three -lexicographically -)

    The key point is mentioned in the answer above

    think of it as an element is before another alphabetically not element is greater than an element and in this case consider all the tuple elements as one string.

提交回复
热议问题