Juste au cas où vous voudriez quelque chose qui puisse fonctionner avec itertools.product
Vous pouvez également essayer ceci (nous serons ravis d'apporter des modifications si cela ne correspond pas à vos données "réelles" - c'est un problème intéressant :) ). Cela pourrait être résumé en moins de lignes, mais cela perd beaucoup en lisibilité, donc j'espère que cela sera quelque peu utile :
from itertools import groupby, product
from operator import itemgetter
the_list = ['A1','A2','A3','B1','B2','B3','C1','C2','C3','D1','D2','D3']
# In order to work properly with groupby, we sort the list by the
# number at the end of the string
s = sorted(the_list, key=itemgetter(-1))
# Now we create a list of lists, each sub-list containing values
# with the same ending number (i.e. ['A1', 'B1', 'C1', 'D1'])
j = [list(g) for _, g in groupby(s, key=itemgetter(-1))]
# Now we create our final list
results = []
# Here we iterate through our grouped lists, using product
# similar to how you did before to create the combined strings
for index, r in enumerate(j):
# This is the piece that lets us 'loop' the list -
# on the first iteration, the value is -(3)+1+0 = -2,
# which we use as our list index. This will return the item
# 'ahead' of the current one in our main list, and when it
# reaches the last (index=2) item, the value is -(3)+1+2 = 0 (beginning)
inc = -len(j) + 1 + index
# Now we just iterate through the items in our sub-list, pairing with
# the items in the 'next' sub-list
for val in r:
results += [k+v for k, v in product([val], j[inc])]
print results
Sortie :
['A1A2', 'A1B2', 'A1C2', 'A1D2',
'B1A2', 'B1B2', 'B1C2', 'B1D2',
'C1A2', 'C1B2', 'C1C2', 'C1D2',
'D1A2', 'D1B2', 'D1C2', 'D1D2', '
A2A3', 'A2B3', 'A2C3', 'A2D3',
'B2A3', 'B2B3', 'B2C3', 'B2D3',
'C2A3', 'C2B3', 'C2C3', 'C2D3',
'D2A3', 'D2B3', 'D2C3', 'D2D3',
'A3A1', 'A3B1', 'A3C1', 'A3D1',
'B3A1', 'B3B1', 'B3C1', 'B3D1',
'C3A1', 'C3B1', 'C3C1', 'C3D1',
'D3A1', 'D3B1', 'D3C1', 'D3D1']