0

I have a list of lists like:

myList = [
    ["name1", [12, 89]],
    ["name2", [37, 2]],
    ["name3", [5, 4]],
    ["name4", [67, 998]]
]
  • The first element inside the inner list is the name
  • The second element inside the inner list is another list with two numbers

I want to use the sort() method to sort the list by:

  1. Name
  2. number1
  3. number2

For example, for the first element, sort by:

  1. "name1"
  2. 12
  3. 89

Can this be achieved with lambda functions?

To sort by name I did: myList.sort(key = lambda x: x)

How can I use lambda functions to sort by 2. and 3. (the numbers)

Desired Output

  • Sort by "Name" gives:
myList = [
    ["name1", [12, 89]],
    ["name2", [37, 2]],
    ["name3", [5, 4]],
    ["name4", [67, 998]]
]
  • Sort by "Number1" gives:
myList = [
    ["name3", [5, 4]],
    ["name1", [12, 89]],
    ["name2", [37, 2]],
    ["name4", [67, 998]]
]
  • Sort by "Number2" gives:
myList = [
    ["name2", [37, 2]],
    ["name3", [5, 4]],
    ["name1", [12, 89]],
    ["name4", [67, 998]]
]
accdias
  • 5,160
  • 3
  • 19
  • 31
Kartikeya Sharma
  • 463
  • 2
  • 5
  • 8

1 Answers1

3

Yes, you can do this with lambdas. Given that your list is

myList = [
    ["name1", [12, 89]],
    ["name2", [37, 2]],
    ["name3", [5, 4]],
    ["name4", [67, 998]]
]
  • Sort by "Name", you sort them alphabetically because ord('1') < ord('2') is True.
# check the 0th element which is the string for each row
myList.sort(key=lambda x: x[0])
  • Sort by "Number1", you just use x[1][0] to access the 0th number of the array in the 1st index
# Take as key the x[1][0] element
myList.sort(key=lambda x: x[1][0])

Similarly with "Number2"

myList.sort(key=lambda x: x[1][1])
accdias
  • 5,160
  • 3
  • 19
  • 31
Countour-Integral
  • 1,138
  • 2
  • 7
  • 21