1

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?

1
  • You can do something like states.sort(key=lambda k: nearby.index(k)). Commented Feb 11, 2022 at 1:13

1 Answer 1

2

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))
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.