Skip to main content
 首页 » 编程设计

python之从列表中删除重复的无序元组

2025年05月04日21zfyouxi

在元组列表中,我只想拥有元组的一个副本,它可能是 (x, y) 或 (y, x)。

所以,在:

# pairs = list(itertools.product(range(3), range(3))) 
pairs = [(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)] 

结果应该是:

result = [(0, 0), (0, 1), (0, 2), (1, 1), (1, 2), (2, 2)] # updated pairs 

这个元组列表是使用 itertools.product() 生成的但我想删除重复项。

我的工作解决方案:

pairs = [(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)] 
 
result = [] 
for pair in pairs: 
    a, b = pair 
    # reordering in increasing order 
    temp = (a, b) if a < b else (b, a) 
    result.append(temp) 
print(list(set(result))) # I could use sorted() but the order doesn't matter 

如何改进?

请您参考如下方法:

你可以使用 combinations_with_replacement

The code for combinations_with_replacement() can be also expressed as a subsequence of product() after filtering entries where the elements are not in sorted order (according to their position in the input pool)

import itertools 
pairs = list(itertools.combinations_with_replacement(range(3), 2)) 
print(pairs) 
 
>>> [(0, 0), (0, 1), (0, 2), (1, 1), (1, 2), (2, 2)]