from itertools import product
list1 = ["a ", "b ", "c ", "d ", "e ", "f ", "g "]
list2 = ["a ", "b*", "c*", "d ", "e*", "f*", "g "]
# figure out which offsets have alternable values
crosses = [a != b for a,b in zip(list1, list2)]
offsets = [i for i,cross in enumerate(crosses) if cross]
# decide which offsets will be swapped
basis = [[0,1] for ofs in offsets]
basis[0] = [0] # only the first half - remainder are mirrors
swaps = product(*basis)
next(swaps, None) # skip base state == (list1, list2)
# print all viable swaps
list3 = list1[:]
list4 = list2[:]
for sw in swaps:
# build output lists
for which,offs in zip(sw, offsets):
list3[offs] = [list1, list2][which][offs]
list4[offs] = [list2, list1][which][offs]
# display output
print("\n{}\n{}".format(list3, list4))
給
['a ', 'b ', 'c ', 'd ', 'e ', 'f*', 'g ']
['a ', 'b*', 'c*', 'd ', 'e*', 'f ', 'g ']
['a ', 'b ', 'c ', 'd ', 'e*', 'f ', 'g ']
['a ', 'b*', 'c*', 'd ', 'e ', 'f*', 'g ']
['a ', 'b ', 'c ', 'd ', 'e*', 'f*', 'g ']
['a ', 'b*', 'c*', 'd ', 'e ', 'f ', 'g ']
['a ', 'b ', 'c*', 'd ', 'e ', 'f ', 'g ']
['a ', 'b*', 'c ', 'd ', 'e*', 'f*', 'g ']
['a ', 'b ', 'c*', 'd ', 'e ', 'f*', 'g ']
['a ', 'b*', 'c ', 'd ', 'e*', 'f ', 'g ']
['a ', 'b ', 'c*', 'd ', 'e*', 'f ', 'g ']
['a ', 'b*', 'c ', 'd ', 'e ', 'f*', 'g ']
['a ', 'b ', 'c*', 'd ', 'e*', 'f*', 'g ']
['a ', 'b*', 'c ', 'd ', 'e ', 'f ', 'g ']
你的意思列表?因爲AFAIR集合通常是無序的而且沒有索引。 –
哎呀,我想我會 - 謝謝!我一直在使用集合(以避免任何重複的條目),但顯然這個比較順序很重要,所以我可以切換到列表。讓我更新這個問題... – JHawkins
一種方法是,你可以形成一個索引列表,其中的集合元素是不同的。在你的情況[1,2]。然後在此列表上使用itertools.combinations,它將表示元素交換髮生的位置。您將不得不刪除重複的條目。 –