【问题标题】:Finding the intersection between several sets in a list查找列表中多个集合之间的交集
【发布时间】:2020-03-26 11:45:08
【问题描述】:

我有一个列表,其中包含多个具有不同名称和字符串值的集合 {}。

例如。

set1 = {"a", "santa", "clock"}
search = {"why", "is", "santa", "nice"}

list_of_sets = [set1, search]

我想通过一个函数找到列表中集合之间的交集:

def intersection_between_sets_from_list(list_of_sets):
    """ find the intersection between the sets here"""
    return intersection_strings

知道在“”中使用什么代码在这里找到集合之间的交集“””。

【问题讨论】:

    标签: python string set intersection


    【解决方案1】:

    如果您想找到列表中所有集合之间的交集,您可以迭代 list_of_set 并找到当前集合和您的时间集合之间的交集,如下所示:

    tmp = list_of_sets[0]
    for e in list_of_sets:
        tmp = tmp.intersection(e)
    

    但是python语言上的这个操作可以做:

    reduce(lambda x, y: x.intersection(y), list_of_sets)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-03-18
      • 1970-01-01
      • 2015-03-06
      • 1970-01-01
      • 1970-01-01
      • 2020-07-08
      • 2015-08-19
      • 2013-02-08
      相关资源
      最近更新 更多