Grouping up elements from a list in Python 2.7
<p>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:</p>

<pre><code>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
</code></pre>

<p>result is something like</p>

<pre><code>['202', 1]
['213', 2]
['210', 2]
['211', 2]
['208', 2]
['304', 1]
['107', 2]
['133', 1]
['132', 1]
['131', 2]
</code></pre>

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

<pre><code>A ['133', 1]
  ['132', 1]
  ['131', 2]
B ['202', 1]
  ['213', 2]
C ['304', 1]
  ['107', 2]
  ['210', 2]
  ['211', 2]
  ['208', 2]
</code></pre>

<p>Note that: </p>

<ul>
<li>in the final result I will need 5 groups (A, B, C, D, E)</li>
<li>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</li>
<li>it would be perfect, but not mandatory, if the elements in each group would be sorted numerically.</li>
<li>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 <em>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)</em>.</li>
</ul>

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

<p>Thanks in advance!</p>

<p>One (probably not most elegant) solution would be to define a dictionary with the mappings and then lookup the name of the group to which the element belongs to. </p>

<pre><code>elements = { "133": "A", "132": "A", 
             "202": "B", 
              ... }
</code></pre>

<p>The elements can then be added to a new dictionary with group names as keys:</p>

<pre><code>groups = {"A":[], "B": [], ...}
for element, count in a:
    group = elements[element]
    groups[group].append( (element, count) )

for group in groups:
    groups[group].sort()                   # sort by element
    for element, count in groups[group]:
        print "%s %s %s" % (group, element, count)
</code></pre>

python arrays list python-2.7 count