两个列表的独特组合 - 每个索引位置的比较

时间:2014-04-13 16:36:16

标签: python

我搜索得非常彻底,并没有找到任何信息 - 希望我没有错过任何东西。我有两个清单:

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个以上项目的更大列表。

1 个答案:

答案 0 :(得分: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 ']