确保从元组列表中返回唯一的元组[关闭]

问题描述 投票:0回答:1

在下面给定的列表中,我想确保元组唯一出现。我的元组只有两个元素。包含两个以上元素的元组超出范围

原始列表:

[("a", "b"), ("c", "d"), ("b", "a"), ("e", "f"), ("a", "e"), ("f", "e")]

预期输出:

[("a", "b"), ("c", "d"), ("e", "f"), ("a", "e")]

我尝试了以下方法:

def flip_and_remove_duplicates(tuple_list):
    seen = set()  # Set to store unique flipped tuples
    result = []
    for tup in tuple_list:
        flipped_tup = tup[::-1]  # Flip the tuple elements
        if flipped_tup not in seen:
            seen.add(flipped_tup)
            result.append(flipped_tup) 
    return result

上述函数翻转元素,但不保留元组之间的唯一性。

python list dictionary tuples
1个回答
0
投票

检查翻转和未翻转的项目:

test = [("a", "b"), ("c", "d"), ("b", "a"), ("e", "f"), ("a", "e"), ("f", "e")]

def flip_and_remove_duplicates(tuple_list):
    result = []
    seen = set()
    for a,b in tuple_list:
        if (a,b) not in seen and (b,a) not in seen:
            seen.add((a,b))
            result.append((a,b))
    return result

print(flip_and_remove_duplicates(test))

输出:

[('a', 'b'), ('c', 'd'), ('e', 'f'), ('a', 'e')]
© www.soinside.com 2019 - 2024. All rights reserved.