Python: sorting string numbers not lexicographically

前端 未结 5 1037
猫巷女王i
猫巷女王i 2020-11-29 14:13

I have an array of string-numbers, like:

numbers = [\'10\', \'8\', \'918\', \'101010\']

When I use sorted(numbers), I get them

5条回答
  •  谎友^
    谎友^ (楼主)
    2020-11-29 14:39

    all elements types are string,

     >>> x=['4', '5', '29', '54', '4', '0', '-214', '542', '-64', '1', '-3', '6', '-6']
     >>> max(x)
     '6'
    

    It "orders" the words alphabetically and returns the one that is at the bottom of the alphabetic list

    Few more examples:

        >>> list1 = ['kyle', 'dhamu']
        >>> max(list1)
        'kyle'
    

    returns kyle because k is after d

    Also remember from python3.7 you cannot mix strings and integers to use max function. Below is the example

    >>> mix_list = ['my', 'name', 'is', 1 ]
    >>> max(mix_list)
    Traceback (most recent call last):
      File "", line 1, in 
    TypeError: '>' not supported between instances of 'int' and 'str'
    
                                                                                                                   
    

提交回复
热议问题