Given two lists with suffixes:
l1 = ['C_1', 'B_1', 'A']
l2 = ['B_2', 'C_2', 'D']
I want to combine them like this:
['C_1', 'C_2', 'B_1', 'B_2', 'A', 'D']
Elements are to be combined with l1
as the anchor. This means, if C_*
comes before B_*
in l1
, the same ordering will be preserved in the output. Furthermore, elements with the same prefix C_*
will be grouped together, in increasing order of suffix. Elements with a suffix are placed in the order in which they appear, as you see above.
You can assume that all elements in l1
have suffix _1
, and all elements in l2
have suffix _2
.
I've tried this:
from collections import OrderedDict
from itertools import chain
o = OrderedDict()
for x in l1 + l2:
o.setdefault(x.split('_')[0], []).append(x)
result = list(chain.from_iterable(o.values()))
Which works, but was wondering if there were any more succinct ways of doing this.
Edit:
The suffix is just a stand in for which list that element appears in. Say I have C_1
from l1
, and C_2
from l2
, then C_*
elements appear based on which was in l1
and which was in l2
, in the final list (so, it'd be ... C_1, C_2...
).
Furthermore, all elements in l1
and l2
are unique wrt each other and themselves. Hope that helps.
l2
matter? not in your sample data as there's only one element without suffix/group froml1
l1
ordering is the anchor here. The ordering ofl2
elements wrt each other in the final list doesn't matter.