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

后端 未结 5 1313
天涯浪人
天涯浪人 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 07:01

    You can trivially sort a list of strings with built-in sorted method. Even if the objects in your list are more complex, you can still use sorted. Just pass a custom key parameter to use the second item from the inner list as the key in ordering comparisons:

    result = sorted(format, key=lambda x: x[1])
    

    Finally switch to your sorting function natsorted (from natsort package) and you end up with the desired, naturally sorted, result list:

    from natsort import natsorted
    result = natsorted(format, key=lambda x: x[1])
    

提交回复
热议问题