首页 > 解决方案 > 找出一个元组是否包含在另一个在 Python 中重复的元组中

问题描述

Tuple1 = (1,2,2)
TupleList = [(1,2,3), (1,2,3,2)]

我想在TupleList中搜索作为Tuple1超集的任何元组。结果应该是在这种情况下:

(1,2,3,2)

但是如果我使用 .issuperset() 函数,它不会考虑到Tuple1中 2 的重复。

如何解决这个问题呢?

标签: pythonlistsettuples

解决方案


如果您需要考虑元素频率,这可能是该实用程序的一个很好的collections.Counter用途。

from collections import Counter


tuple_1 = (1, 2, 2)
tuple_list = [(1, 2, 3), (3, 4, 1), (1, 2, 3, 2)]


def find_superset(source, targets):
    source_counter = Counter(source)
    for target in targets:
        target_counter = Counter(target)
        if is_superset(source_counter, target_counter):
            return target

    return None  # no superset found


def is_superset(source_counter, target_counter):
    for key in source_counter:
        if not target_counter[key] >= source_counter[key]:
            return False
    return True


print(find_superset(tuple_1, tuple_list))

输出:

(1, 2, 3, 2)

推荐阅读