from itertools import combinations
data_list = [[3, 6], [1, 5], [2, 3], [2, 6], [0, 4], [2, 4], [0, 2]]
# doc for the combination function:
# https://docs.python.org/3/library/itertools.html#itertools.combinations
all_triple_pairs = list(combinations(data_list, 3))
# obtain the unique set of digits in all possible combination of triples
digit_sets = [set(d for pair in trip for d in pair) for trip in all_triple_pairs]
# the duplicates occur only when there are 3 unique digits
dup_inds = [i for i, s in enumerate(digit_sets) if len(s)==3]
# get the actual triples of pairs with a duplicated pair element
duplicates = [all_triple_pairs[i] for i in dup_inds]
# mark the last pair (as requested) in each duplicated triple for removal
pairs_to_remove = [trip[-1] for trip in duplicates]
answer = [pair for pair in data_list if pair not in pairs_to_remove]
for p in answer:
print(p)
[3, 6]
[1, 5]
[2, 3]
[0, 4]
[2, 4]
我确信有一种更有效、更优雅的方法来解决这个问题(更不用说,我甚至没有为它们的性能而费心使用numpy向量)。但这里有一个暴力解决方案,使用列表理解。你知道吗
相关问题 更多 >
编程相关推荐