I have a list as following:
['Pizza', '1', 'Apple', 2, 'Pizza', '1', 'Orange', '5', 'Pear', '4']
And I want to sort it according to every second element in the list, so the output would be the following:
[‘Pizza’, ‘1’, ‘Pizza’, ‘1’, ‘Apple’, 2, ‘Pear’, ‘4’, ‘Orange’, ‘5’]
How can I do this?
>Solution :
group the list into tuples:
mylist = ['Pizza', '1', 'Apple', 2, 'Pizza', '1', 'Orange', '5', 'Pear', '4']
grouped_list = [(k, v) for k, v, in zip(mylist[::2], mylist[1::2])]
sort them by value:
sorted_list = sorted(grouped_list, key=lambda x:x[1])
gives:
[('Pizza', 1), ('Pizza', 1), ('Apple', 2), ('Pear', 4), ('Orange', 5)]
back into a list:
sum([[k, v] for k, v in sorted_list], [])