How can you sort a list of names followed by a number in numerical order?


How can you sort a list of names followed by a number in numerical order?

list = ["Colin",1,"Chris",3,"John",6,"Peter",10,"Kyle",2]

I want the list to end up looking like:

list = ["Colin",1,"Kyle",2,"Chris",3,"John",6,"Peter",10]

Answer

This is one solution utilising itertools.

from itertools import chain, islice
from operator import itemgetter

lst = ["Colin",1,"Chris",3,"John",6,"Peter",10,"Kyle",2]

zipper = zip(islice(lst, 0, None, 2), islice(lst, 1, None, 2))
sorter = sorted(zipper, key=itemgetter(1))
res = list(chain.from_iterable(sorter))

['Colin', 1, 'Kyle', 2, 'Chris', 3, 'John', 6, 'Peter', 10]

Note you should never name a variable after a class, so use lst instead of list.


A much better idea is to use a more appropriate data structure, such as OrderedDict:

from collections import OrderedDict

res = OrderedDict(sorted(zip(lst[1::2], lst[::2]), key=lambda x: x[0]))

OrderedDict([(1, 'Colin'),
             (2, 'Kyle'),
             (3, 'Chris'),
             (6, 'John'),
             (10, 'Peter')])