2014-04-13 27 views
1

我已經非常徹底地搜索了,並且沒有找到任何信息 - 希望我沒有錯過任何內容。我有兩個列表:兩個列表的唯一組合 - 每個索引位置的比較

list1 = (a, b, c, d) 
list2 = (a, b*, c*, d) 

我想生成所有可能的唯一2列表配對,只查找每個索引值的差異。例如,這裏的結果將是:

list1_new = (a, b*, c, d) 
list2_new = (a, b, c*, d) 

注:我不在乎list1list2,即區分,list1_new = (a, b*, c*, d)不會被認爲是獨一無二的,因爲它原來的list2匹配。

我玩過itertools,但一直未能弄清楚如何比較每個索引位置。

我在這個例子中使用了小列表,但實際上我會有更多的10+列表。

+0

你的意思列表?因爲AFAIR集合通常是無序的而且沒有索引。 –

+0

哎呀,我想我會 - 謝謝!我一直在使用集合(以避免任何重複的條目),但顯然這個比較順序很重要,所以我可以切換到列表。讓我更新這個問題... – JHawkins

+0

一種方法是,你可以形成一個索引列表,其中的集合元素是不同的。在你的情況[1,2]。然後在此列表上使用itertools.combinations,它將表示元素交換髮生的位置。您將不得不刪除重複的條目。 –

回答

0
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 '] 
+0

對不起,在編輯之前發表評論。我認爲這是完美的!很酷,謝謝! – JHawkins