【问题标题】:Find out if a tuple is contained into another one with repetitions in Python找出一个元组是否包含在另一个在 Python 中重复的元组中
【发布时间】:2019-12-24 17:11:45
【问题描述】:
Tuple1 = (1,2,2)
TupleList = [(1,2,3), (1,2,3,2)]

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

(1,2,3,2)

但是如果我使用.issuperset()函数的话,就不会考虑到Tuple1里面的2的重复了。

如何解决这个问题?

【问题讨论】:

  • Tuple1 不在元组(1,2,3) 中,作为元组。作为一个集合,是的。你想要哪一个?另外:你只想要最大的超集吗?
  • 但作为一个集合,(1,2,2) 将被视为 (1,2)。我想在 TupleList 中找到包含 Tuple1 的所有元素(包括重复)的元组。
  • 你需要元素按顺序出现吗?
  • issuperset 在片场运行,IMO 你必须编写逻辑来计算频率,并在此基础上获得所需的列表
  • 元素不需要按顺序出现,只要出现就行(根据Tuple1中给出的次数)

标签: python list set tuples


【解决方案1】:

如果您需要考虑元素频率,这可能是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)

【讨论】:

  • 很好,但它只给出了第一个超集。放弃它
【解决方案2】:
from collections import Counter

def contains(container, contained):
  " True if all values in dictionary container >= values in contained"
  return all(container[x] >= contained[x] for x in contained)

def sublist(lst1, lst2):
  " Detects if all elements in lst1 are in lst2 with at least as many count "
  return contains(Counter(lst1), Counter(lst2), )

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

# List of tuples from TupleList that contains Tuple1
result = [x for x in TupleList if sublist(x, Tuple1)]

print(result)

>>>[(1, 2, 3, 2)]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-01-30
    • 2017-03-03
    • 2021-12-30
    • 2022-01-21
    • 2020-02-25
    • 2016-11-16
    相关资源
    最近更新 更多