I have a list of lists and I want to learn how to sort the list by the element at index 1 but also sorted by the element at index 2 if index 1 returns the same number for two items.
I want to do this without the use of inbuilt functions and methods so that I can continue to develop my understanding of lists and how to manipulate them.
To recap:
- I have a list of lists
- Each sublist has the same number of elements
- I am trying to sort them in descending order by creating a new unsorted list which is a copy of the original list (I don't want to modify the original unsorted list) and looping over the copy of the unsorted list to grab the highest number in (from index 1) and then appending that to a newly created sorted_lists variable
- I then remove that list from the original unsorted list
- I repeat the process until one by one the remaining lists with the highest value is added to the new sorted list and removed from the original list
I have tried a few different things but cannot get it to work. Any help would be appreciated.
# initialising list
food_list = (
["banana", 10, "f", "yellow"],
["apple", 12, "f", "red"],
["pear", 60, "f", "green"],
["mango", 5, "f", "yellow"],
["lettuce", 3, "v", "green"],
["beans", 20, "v", "green"],
["red capsicum", 1, "v", "red"],
["corn", 20, "v", "yellow"],
)
unsorted_food_list_copy = food_list
sorted_food_list = []
while len(unsorted_food_list_copy) != 0:
maximum = 0
for food in unsorted_food_list_copy:
if food[1] > maximum:
maximum = food[1]
sorted_food_list.append(maximum)
unsorted_food_list_copy.remove(maximum)
I have also tried this:
# initialising list
food_list = (
["banana", 10, "f", "yellow"],
["apple", 12, "f", "red"],
["pear", 60, "f", "green"],
["mango", 5, "f", "yellow"],
["lettuce", 3, "v", "green"],
["beans", 20, "v", "green"],
["red capsicum", 1, "v", "red"],
["corn", 20, "v", "yellow"],
)
unsorted_food_list_copy = food_list
sorted_food_list = []
while unsorted_food_list_copy:
min = unsorted_food_list_copy[1]
for x in unsorted_food_list_copy:
if x < min:
min = x
sorted_food_list.append(min)
unsorted_food_list_copy.remove(min)