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

后端 未结 5 1311
天涯浪人
天涯浪人 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:42

    The same solution can be used here

    print sorted(format_data, key=lambda x: (int(x[1].split(None, 1)[0]) if x[1][:1].isdigit() else 999, x))
    

    Note the x[1] instead of just x. x[1] means the second element in x.

    Result:

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

提交回复
热议问题