Grouping up elements from a list in Python 2.7
Question: Ok, I got a huge text. I extract matches with regex (omitted here because it
doesn't matter and I'm bad at this so you don't see how ugly my regex is :) )
and count them. Then, for readability, I split the elements and print them in
the fashion I need:

    
    
    import re
    f = re.findall(r"(...)", PF)
    a = [[y,f.count(y)] for y in set(f)]
    (' '.join(map(str, j)) for j in w)
    for element in w:
        print element
    

result is something like

    
    
    ['202', 1]
    ['213', 2]
    ['210', 2]
    ['211', 2]
    ['208', 2]
    ['304', 1]
    ['107', 2]
    ['133', 1]
    ['132', 1]
    ['131', 2]
    

What I need is to group up the elements, so that I get an output like

    
    
    A ['133', 1]
      ['132', 1]
      ['131', 2]
    B ['202', 1]
      ['213', 2]
    C ['304', 1]
      ['107', 2]
      ['210', 2]
      ['211', 2]
      ['208', 2]
    

Note that:

  * in the final result I will need 5 groups (A, B, C, D, E)
  * the elements can vary, for example tomorrow 131 might not be present but I might have 232 that goes in group A and the number of elements is different every day
  * it would be perfect, but not mandatory, if the elements in each group would be sorted numerically.
  * Might sound obvious but I'll make it clear anyway, I know exactly which elements need to go in which group. If it is of any help, group _A can contain (102, 103), B(104,105,106,201,202,203), C(204,205,206,301,302,303,304), D(107,108,109,110,208,209,210,211,213,305,306,307), E(131,132,133,231,232)_.

The script needs to take the results that are present that day, compare them
to the list above, and sort into the relative groups.

Thanks in advance!


Answer: You can set up a hash that maps elements to groups. You can then transform
each array item from [element,count] to (group,element,count) _(using a tuple
to make it more easily sortable and such)_. Sort that array, then use a loop
or `reduce` to transform that into your final output.

    
    
    mapElementsToGroups = {'131': 'A', '202': 'B', '304': 'C', …}
    
    elementsFoundByGroup = {}
    for (group, element, count) in sorted(
                [(mapElementsToGroups[item[0]], item[1], item[2])
                    for item in a]
            ):
        elementsFoundByGroup[group] = elementsFoundByGroup.get(group, []) + [(element, count)]
    

You now have a dictionary mapping each group name found to the list of
elements and counts found within that group. The quick print is:

    
    
    print [
                group + " " +
                elements.join("\n " + " "*len(group))
                    for (group,elements) in sorted(elementsFoundByGroup.items())
            ].join("\n")
    

