将字母与其值相关联并在 python 中对输出进行排序

Associate letters with its value and sort output in python

请帮忙解决这个问题。我有这样的输入:

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

我想以排序方式打印与每个字母相关的数字,如下所示:

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

到目前为止,我能够在数组 b 中存储字母和数字,但是当我尝试创建类似字典的数组来连接单个字母及其值时,我遇到了这个错误。

 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

我正在开发 python 3.6 以防万一。提前致谢。

我们会将字符串分成对,对这些对进行排序,然后使用 groupbyenumerate 得出索引。

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)

给我们

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