Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Sort list using every second element

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’]

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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], [])
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading