Sort list of strings by substring using Python
list, python, sorting, string, substring
Solution
Write a function that returns the two pieces of information you care about from each email:
def email_sort_key(email):
"""Find two pieces of info in the email, and return them as a tuple."""
# ...search, search...
return "location", "incident_date"
Then, use that function as the key for sorting:
emails.sort(key=email_sort_key)
The sort key function is applied to all the values, and the values are re-ordered based on the values returned from the key function. In this case, the key function returns a tuple. Tuples are ordered lexicographically: find the first unequal element, then the tuples compare as the unequal elements compare.
Problem
I have a list of strings, each of which is an email formatted in almost exactly the same way. There is a lot of information in each email, but the most important info is the name of a facility, and an incident date. I'd like to be able to take that list of emails, and create a new list where the emails are grouped together based on the "location_substring" and then sorted again for the "incident_date_substring" so that all of the emails from one location will be grouped together in the list in chronological order. The facility substring can be found usually in the subject line of each email. The incident date can be found in a line in the email that starts with: "Date of Incident:". Any ideas as to how I'd go about doing this?