Sorting a mixed list of ints and strings

后端 未结 3 1836
盖世英雄少女心
盖世英雄少女心 2020-12-12 04:32

I am trying to sort the following mixed list of ints and strings, but getting a TypeError instead. My desired output order is sorted integers then sorted strings.

         


        
相关标签:
3条回答
  • 2020-12-12 05:13

    With function key

    def func(i):
        return isinstance(i, str), i
    
    stuff = ['Tractor', 184 ,'Lada', 11 ,'Ferrari', 5 , 'Chicken' , 68]
    stuff.sort(key=func)
    
    for x in stuff:
        print(x)
    

    Change type str to int to get strings first.

    0 讨论(0)
  • 2020-12-12 05:24

    I can see from your comment that you want integers to be sorted first then strings.

    So we could sort two separate lists and join them as follows:

    x=[4,6,9,'ashley','drooks','chay','poo','may']
    intList=sorted([i for i in x if type(i) is int])
    strList=sorted([i for i in x if type(i) is str])
    print(intList+strList)
    

    Output:

    [4, 6, 9, 'ashley', 'chay', 'drooks', 'may', 'poo']

    0 讨论(0)
  • 2020-12-12 05:26

    You can pass a custom key function to list.sort:

    x = [4,6,9,'ashley','drooks','chay','poo','may']
    x.sort(key=lambda v: (isinstance(v, str), v))
    
    # result:
    # [4, 6, 9, 'ashley', 'chay', 'drooks', 'may', 'poo']
    

    This key function maps each element in the list to a tuple in which the first value is a boolean (True for strings and False for numbers) and the second value is the element itself, like this:

    >>> [(isinstance(v, str), v) for v in x]
    [(False, 4), (False, 6), (False, 9), (True, 'ashley'), (True, 'chay'),
     (True, 'drooks'), (True, 'may'), (True, 'poo')]
    

    These tuples are then used to sort the list. Because False < True, this makes it so that integers are sorted before strings. Elements with the same boolean value are then sorted by the 2nd value in the tuple.

    0 讨论(0)
提交回复
热议问题