'How to sort part of values in list? [closed]

I want to sort the value which startswith chapter in list, but I have no idea to implement this.

my list

["prologue", "chapter 1", "chapter 3", "chapter 2", "sick", "chapter 5", "chapter 4"]

expected

["prologue", "chapter 1", "chapter 2", "chapter 3", "sick", "chapter 4", "chapter 5"]

Edited

What should the output look like if instead of 'chapter 2' you had 'chapter 22' in the same position in the list? – Lancelot du Lac

I don't have this problem yet. But if so, I will want this one.

['prologue', 'chapter 1', 'chapter 3', 'sick', 'chapter 4', 'chapter 5', 'chapter 22']

use @mosc9575 solution but change the sorted() to natsorted() module

The result will be

['prologue', 'chapter 1', 'chapter 3', 'chapter 4', 'sick', 'chapter 5', 'chapter 22']


Solution 1:[1]

Here is one solution, but I am sure there are a lot more.

my_list = ["prologue", "chapter 1", "chapter 3", "chapter 2", "sick", "chapter 5", "chapter 4"]
to_sort = []
to_sort_index = []
for i, item  in enumerate(my_list):
    if item.startswith('chapter'):
        to_sort.append(item)
        to_sort_index.append(i)
for i, item in zip(to_sort_index, sorted(to_sort)):
    my_list [i] = item

Result:

['prologue',
 'chapter 1',
 'chapter 2',
 'chapter 3',
 'sick',
 'chapter 4',
 'chapter 5']

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1