Home > Back-end >  Sorting a list of strings with another list of strings
Sorting a list of strings with another list of strings

Time:02-17

I am trying to sort an Event class by nearest geographical location. I have a list of event objects with the state the event takes place in event.state = 'Wyoming'. I also have a list of nearby states nearby = ['Wyoming', 'Colorado', 'Nebraska', 'South Dakota', 'etc']

I would like to implement a custom sort method

def sort_by_nearby_location():
  # Take event.state and compare to nearby states list and return sorted list

Is there a method in python that would allow me sort my list of events by their state according to the order I have set in my nearby list? What would be the best way to tackle this type of probelem?

CodePudding user response:

sorted() takes a key argument. This argument can be a lambda or a function that transforms your original list element, for instance to the index of that element in your nearby list.

sorted(events, key=lambda event: nearby.index(event.state))
  • Related