Associate letters with its value and sort output in python

35 Views Asked by At

Please help on this. I have an input like this:

 a = """A|9578
 C|547
 A|459
 B|612
 D|53
 B|6345
 A|957498
 C|2910"""

I want to print in sorted way the numbers related with each letter like this:

 A_0|459
 A_1|957498
 A_2|9578
 C_0|2910
 C_1|547
 B_0|612
 B_1|6345
 D_0|53

So far I was able to store in array b the letters and numbers, but I'm stuck when I try to create dictionary-like array to join a single letter with its values, I get this error.

 b = [i.split('|') for i in a.split('\n')]
 c = dict()
 d = [c[i].append(j) for i,j in b]
 >>> d = [c[i].append(j) for i,j in b]
 Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
 File "<stdin>", line 1, in <listcomp>
 TypeError: list indices must be integers or slices, not str

I'm working on python 3.6 just in case. Thanks in advance.

1

There are 1 best solutions below

7
On BEST ANSWER

We'll split the string into pairs, sort those pairs, then use groupby and enumerate to come up with the indices.

from itertools import groupby
from operator import itemgetter

def process(a):
    pairs = sorted(x.split('|') for x in a.split())
    groups = groupby(pairs, key=itemgetter(0))
    for _, g in groups:
        for index, (letter, number) in enumerate(g):
            yield '{}_{}|{}'.format(letter, index, number)

for i in process(a): print(i)

gives us

A_0|459
A_1|957498
A_2|9578
B_0|612
B_1|6345
C_0|2910
C_1|547
D_0|53