爲防萬一你想要一些可能與itertools.product
一起工作的東西,你可以試試這個(如果它不符合你的'真實'輸入,那麼就試試這個(這是一個有趣的問題:))。這可以被包裝成更少的行,但它失去了很多的可讀性,所以希望這將是有點用的:
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
輸出:
['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']
這是你可能就要有用循環手動寫入。用英文分解(就像你已經開始),然後從那裏開始。祝你好運。 –
是的,它是有效的... –
我很困惑......你說它不能以'B2'開始,但'B2A3'是有效的...... – Volatility