#!/usr/bin/env python
from itertools import groupby
pairs = """
O1-P1-O2
O3-P2-O4
O5-P3-O1
O1-P4-O2
O2-P5-O1
O1-P6-O5
O7-P7-O8
""".split()
def lex_order(pair):
"""'O2-P5-O1' -> ['01', '02']"""
return sorted(pair.split('-')[::2])
data = sorted(pairs, key=lex_order)
for key, group in groupby(data, key=lex_order):
print "key=%(key)s, pairs=%(pairs)s" % dict(key=key, pairs=list(group))
输出:
key=['O1', 'O2'], pairs=['O1-P1-O2', 'O1-P4-O2', 'O2-P5-O1']
key=['O1', 'O5'], pairs=['O5-P3-O1', 'O1-P6-O5']
key=['O3', 'O4'], pairs=['O3-P2-O4']
key=['O7', 'O8'], pairs=['O7-P7-O8']
#!/usr/bin/env python
from collections import defaultdict
pairs = """
O1-P1-O2
O3-P2-O4
O5-P3-O1
O1-P4-O2
O2-P5-O1
O1-P6-O5
O7-P7-O8
""".split()
bags = defaultdict(list)
for pair in pairs:
i, _, j = pair.split('-') # 'O2-P5-O1' -> ['02', 'P5', '01']
bags[min(i,j), max(i,j)].append(pair)
import pprint;
pprint.pprint(dict(bags))
输出:
{('O1', 'O2'): ['O1-P1-O2', 'O1-P4-O2', 'O2-P5-O1'],
('O1', 'O5'): ['O5-P3-O1', 'O1-P6-O5'],
('O3', 'O4'): ['O3-P2-O4'],
('O7', 'O8'): ['O7-P7-O8']}