-3

I'm trying to sort two lists of lists. Each one is a string.

list1 = [[john, 456, 789], [bill, 483, 293], [jack, 292, 483]]
list2 = [[bill, 483, 293], [john, 2982, 272] [jack, 237, 411]]

As you can see the two lists of lists have a different order, and each name has different numbers.

I'm looking to create a sorted version of each list, sorted by the name (the first index of each inner list) ONLY. So it would look like:

list1 = [[john, 456, 789], [bill, 483, 293], [jack, 292, 483]]
list2 = [[john, 2982, 272], [bill, 483, 293],  [jack, 299, 411]]

How can i achieve this?

Quack
  • 133
  • 7
  • 1
    Are ``john``, ``bill``, ``jack`` strings or variables? – Shaun Han Jun 30 '21 at 20:02
  • If i understood you correctly, you want to sort by the name, however you demonstrated the results as john, bill and jack, while sorting [by the ABC] should result in Bill, Jack and John. they also might just be variables that contain other strings, nobody knows. – Jonathan1609 Jun 30 '21 at 20:02
  • @Jonathan1609 i'll edit for clarification. – Quack Jun 30 '21 at 20:04
  • Also consider simply storing one or both sets of data in a dictionary e.g. `dict2['john'] = (456, 789)`, unless you absolutely need both in lists. – jarmod Jun 30 '21 at 20:04
  • 1
    What you are looking for could be [sorting with a custom key](https://wiki.python.org/moin/HowTo/Sorting/). There has been [previous answer](https://stackoverflow.com/a/11850552/14426823) on this. You would do this: `list1.sort(key=lambda arr: arr[0])` – Bao Huynh Lam Jun 30 '21 at 20:06
  • @BaoHuynhLam This will work thankyou. – Quack Jun 30 '21 at 20:10
  • Does this answer your question? [Custom Python list sorting](https://stackoverflow.com/questions/11850425/custom-python-list-sorting) – cigien Jun 30 '21 at 23:52

1 Answers1

1

Assuming the names are all strings, you can sort list2 based on the order of the names in list1:

list1 = [['john', 456, 789], ['bill', 483, 293], ['jack', 292, 483]]
list2 = [['bill', 483, 293], ['john', 2982, 272], ['jack', 237, 411]]

names = [l[0] for l in list1]
list2.sort(key=lambda x: names.index(x[0]))
print(list2)

Output:

[['john', 2982, 272], ['bill', 483, 293], ['jack', 237, 411]]

The code will still work if the names are variables not strings.

Shaun Han
  • 2,676
  • 2
  • 9
  • 29