-1

I want to create a function that sorts a list that its elements are many other lists composed of words and numbers as shown next :

   [[4, "apple"], [2, "orange"], [5, "waterlimon"] [1, "pineapple"], [3, "bananas"]]

However, I want the output to be :

   [[1, "pineapple"], [2, "orange"], [3, "bananas"], [4, "apple"], [5, "waterlimon"]]

Does anyone have any idea how to do this, please? Thank you.

Aismaili
  • 11
  • 2

4 Answers4

1

You can use the sorted function to achieve this. See the documentation here.

l=  [[4, "apple"], [2, "orange"], [5, "waterlimon"], [1, "pineapple"], [3, "bananas"]]
s = sorted(l, key=lambda x: x[0])
print(s)

The key parameter specifies what will be used for comparison in the sort. In this case, it is the first index of the lists that are elements.

Output:

[[1, 'pineapple'], [2, 'orange'], [3, 'bananas'], [4, 'apple'], [5, 'waterlimon']]
Richard K Yu
  • 2,152
  • 3
  • 8
  • 21
0

You don't have to do anything special, Python will sort the sublists based on their content:

>>> x = [[4, "apple"], [2, "orange"], [5, "waterlimon"], [1, "pineapple"], [3, "bananas"]]
>>> sorted(x)
[[1, 'pineapple'], [2, 'orange'], [3, 'bananas'], [4, 'apple'], [5, 'waterlimon']]
>>> 
cdlane
  • 40,441
  • 5
  • 32
  • 81
0

if your list is like your example you have just to use the builtin function sort().

-1

First you need a function/method to indicate what is the key you want to use for ordering. In your case that'll be the first element of the first sublist:

def ordebykey(sequence: List[List]):
    return sequence[0]

Then you use "sorted" function passing the above function as the second (keyword) argument:

ordered = sorted(original_list, key=orderbykey)

Try this out man, I'm on the phone and can't give you the confirmation. Maybe tomorrow I'll fix it up if it doesn't, but this is the way to go.

edit: sorry, it was just a single [0]

NeXuS
  • 1
  • 4