列表元组表示

List Tuple Representing

比方说,我有以下偶数名称列表,结果应该 return 表示对:

['A', 'B', 'C', 'D']
>>> [[('B', 'C'), ('A', 'D')],
     [('A', 'B'), ('C', 'D')],
     [('A', 'C'), ('B', 'D')]]

我写了下面的代码:

import itertools
combinations = list(itertools.combinations(['A', 'B', 'C', 'D'], 2))
result = []

for i in range( 0 , len(combinations) ):
    if (combinations[i-1][0] != combinations[i][0]) & (combinations[i-1][0] != combinations[i][1])  :
        if (combinations[i-1][1] != combinations[i][0]) & (combinations[i-1][1] != combinations[i][1]) :
            zipped = zip(combinations[i], combinations[i-1])
            result.append(list(zipped))
result


但结果如下;

[[('A', 'C'), ('B', 'D')],
 [('B', 'A'), ('C', 'D')]]

我的代码中缺少什么?

这是一个棘手的小问题,尤其是当扩展到四个以上的名称时。我在这里所做的是创建四个名字的所有排列。然后,为了确定唯一性,我对这些对进行排序,并对这些对列表进行排序。然后我保留唯一的。

import itertools
gather = []
for sets in itertools.permutations(['Andrea', 'Bob', 'Cassandra', 'Doug']):
    pairs = sorted([sorted(p) for p in zip(sets[0::2],sets[1::2])])
    if pairs not in gather:
        gather.append(pairs)
from pprint import pprint
pprint(gather)

四个名字的输出:

[[['Andrea', 'Bob'], ['Cassandra', 'Doug']],
 [['Andrea', 'Cassandra'], ['Bob', 'Doug']],
 [['Andrea', 'Doug'], ['Bob', 'Cassandra']],

六个名字的输出:

[[['Andrea', 'Bob'], ['Cassandra', 'Doug'], ['Ethel', 'Fred']],
 [['Andrea', 'Bob'], ['Cassandra', 'Ethel'], ['Doug', 'Fred']],
 [['Andrea', 'Bob'], ['Cassandra', 'Fred'], ['Doug', 'Ethel']],
 [['Andrea', 'Cassandra'], ['Bob', 'Doug'], ['Ethel', 'Fred']],
 [['Andrea', 'Cassandra'], ['Bob', 'Ethel'], ['Doug', 'Fred']],
 [['Andrea', 'Cassandra'], ['Bob', 'Fred'], ['Doug', 'Ethel']],
 [['Andrea', 'Doug'], ['Bob', 'Cassandra'], ['Ethel', 'Fred']],
 [['Andrea', 'Doug'], ['Bob', 'Ethel'], ['Cassandra', 'Fred']],
 [['Andrea', 'Doug'], ['Bob', 'Fred'], ['Cassandra', 'Ethel']],
 [['Andrea', 'Ethel'], ['Bob', 'Cassandra'], ['Doug', 'Fred']],
 [['Andrea', 'Ethel'], ['Bob', 'Doug'], ['Cassandra', 'Fred']],
 [['Andrea', 'Ethel'], ['Bob', 'Fred'], ['Cassandra', 'Doug']],
 [['Andrea', 'Fred'], ['Bob', 'Cassandra'], ['Doug', 'Ethel']],
 [['Andrea', 'Fred'], ['Bob', 'Doug'], ['Cassandra', 'Ethel']],
 [['Andrea', 'Fred'], ['Bob', 'Ethel'], ['Cassandra', 'Doug']]]