3
\$\begingroup\$

Trying to group elements in a list by the their last element. I think this is a good problem to use groupby() from itertools. Here is my solution:

from itertools import groupby

def match_ends(list1):
    """Returns a dictionary of groups of elements whose end elements match
       Returns empty dic if given list was empty
       Ex: list1 = ["abc", "dbc","aba","baa"]
       matched_ends(list1) = { 'c' : ['abc', 'dbc'], 'a' : ['aba', 'baa'] }
"""            
    matched_ends = {} 
    list1 = sorted(list1, key = lambda x: x[-1])
    for key, group in groupby(list1, lambda x: x[-1]):
         matched_ends[key] = list(group)
    return matched_ends

Was this a good approach? Am I missing any key points, or any errors I did not forsee that may yield garbage values instead of the program throwing an Error? Is there a quicker way to group elements based on certain criteria that I have yet to see?

\$\endgroup\$
3
\$\begingroup\$

docstring

Your original method is adequately docmented, but you can format your docstring also according to a general style. This SO answer covers some of the templates.

doctest

If you format your example in the correct way, you can use doctest to test it. This format is also recognised by Sphinx and other documentation tools,

alternative approach

Another approach would be to use a collections.defaultdict(list)

def match_ends(list1):
    result = defaultdict(list)
    for item in list1:
        result[item[-1]].append(item)
    return result

This way you don't have to sort the list first, but need to append to it. If you use python >3.6, the original method will also return a alphabetically sorted dict, while this method will be sorted along the occurrence in the original list.

\$\endgroup\$
  • \$\begingroup\$ I just learned how to use time module and used it between the two functions and I must say yours is much, much faster. I think it's the the sorted() function in my implementation. I'm gunna test it further but thank you for teaching me about proper docstrings! I had no idea there was a format \$\endgroup\$ – Anonymous3.1415 Sep 27 '18 at 18:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.