Home > Back-end >  Sort list using every second element
Sort list using every second element

Time:05-04

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?

CodePudding user response:

group the list into tuples:

mylist = ['Pizza', '1', 'Apple', 2, 'Pizza', '1', 'Orange', '5', 'Pear', '4']
ordered_list = [(k, v) for k, v, in zip(mylist[::2], mylist[1::2])]

sort them by value:

sorted_list = sorted(ordered_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], [])

CodePudding user response:

  1. build tuples
  2. sort
  3. rebuild the list by flattening
data = ["Pizza", "1", "Apple", "2", "Pizza", "1", "Orange", "5", "Pear", "4"]
result = [
    item
    for pair in sorted(
        [(data[i], data[i   1]) for i in range(0, len(data), 2)],
        key=lambda item: item[1],
    )
    for item in pair
]
assert result == ["Pizza", "1", "Pizza", "1", "Apple", "2", "Pear", "4", "Orange", "5"]
  • Related