Python sort list of list containing integer and string with integers inside

后端 未结 5 1372
天涯浪人
天涯浪人 2021-01-14 06:35

How i can use python to sort the list format

format=[\"12 sheet\",\"4 sheet\",\"48 sheet\",\"6 sheet\", \"busrear\", \"phonebox\",\"train\"]
<
5条回答
  •  生来不讨喜
    2021-01-14 06:47

    You can do this:

    lst = [[1L, u'12 sheet', 0],
           [2L, u'4 sheet', 0],
           [3L, u'48 sheet', 0],
           [4L, u'6 sheet', 0],
           [5L, u'Busrear', 0],
           [6L, u'phonebox', 0],
           [7L, u'train', 0]]
    
    def sortby(x):
        try:
            return int(x[1].split(' ')[0])
        except ValueError:
            return float('inf')
    
    lst.sort(key=sortby)
    print lst
    

    Output:

    [[2L, u'4 sheet', 0], [4L, u'6 sheet', 0], [1L, u'12 sheet', 0], [3L, u'48 sheet', 0], [5L, u'Busrear', 0], [6L, u'phonebox', 0], [7L, u'train', 0]]
    

    You can always use fancier list comprehension but readability counts. Which is why you might not feel like modifying the cool solution by falsetru for this slightly changed task.

提交回复
热议问题