如何在python中从数组中删除重复的组合

2024-04-16 17:27:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我应该有一个列表或numpy数组吗

[[3 6]
 [1 5]
 [2 3]
 [2 6]
 [0 4]
 [2 4]
 [0 2]]

既然出现了[3,6]和[2,3],我想去掉第三个可能的2,3和6的组合,即[2,6]。你知道吗

与[0,4]和[2,4]相似,我想去掉第三个可能的0,2和4的组合,即[0,2]

从根本上说,从任何可能的3个数字的组合,只有2个组合出现在第一个应保留,其他应删除。你知道吗

最终输出应为

[[3 6]
 [1 5]
 [2 3]
 [0 4]
 [2 4]]

Tags: numpy列表数字数组
1条回答
网友
1楼 · 发布于 2024-04-16 17:27:13

我确信有一种更有效、更优雅的方法来解决这个问题(更不用说,我甚至没有为它们的性能而费心使用numpy向量)。但这里有一个暴力解决方案,使用列表理解。你知道吗

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]

相关问题 更多 >