【问题标题】:Intersection between all elements of same list where elements are set [duplicate]设置元素的同一列表的所有元素之间的交集[重复]
【发布时间】:2015-02-24 05:56:09
【问题描述】:

我有一个清单-

list_of_sets = [{0, 1, 2}, {0}]

我想计算列表元素之间的交集。我想过这个解决方案:

a =  list_of_sets[0]

b =  list_of_sets[1]

c =  set.intersection(a,b)

此解决方案有效,因为我知道列表元素的数量。 (所以我可以声明尽可能多的变量,如 a、b 等)

我的问题是我无法为另一种情况找到解决方案,其中列表元素的数量是未知的。

注意:使用循环计算列表元素的数量,而不是根据结果创建变量的想法已经过检查。因为我必须将我的代码保存在一个函数中(参数是 list_of_sets),所以我需要一个更可用于任何编号列表的通用解决方案。 p>

编辑 1:

我需要列表中所有元素的解决方案。 (不是成对或 3/4 元素)

【问题讨论】:

  • 对不起,我正在编辑它。

标签: python list python-2.7 python-3.x set


【解决方案1】:

如果你想要all_sets的所有元素之间的交集:

intersection = set.intersection(*all_sets)

all_sets 是一个集合列表。 setset 类型。


对于成对计算,

这会计算列表 all_sets 中 2 个集合的所有无序对的交集。如果您需要 3,则使用 3 作为参数。

from itertools import combinations, starmap
all_intersections = starmap(set.intersection, combinations(all_sets, 2))

如果您确实需要集合 a、b 进行计算,那么:

for a, b in combinations(all_sets, 2):
    # do whatever with a, b

【讨论】:

    【解决方案2】:

    你想要所有集合的交集。那么:

    list_of_sets[0].intersection(*list_of_sets[1:])
    

    应该可以。

    从列表中取出第一个集合,然后将其与其余集合相交(使用 * 解压缩列表)。

    【讨论】:

      【解决方案3】:

      您可以为此使用reduce。如果您使用的是 Python 3,则必须从 functools 导入它。这是一个简短的演示:

      #!/usr/bin/env python
      
      n = 30
      m = 5
      
      #Find sets of numbers i: 1 <= i <= n that are coprime to each number j: 2 <= j <= m
      list_of_sets = [set(i for i in range(1, n+1) if i % j) for j in range(2, m+1)]
      
      print 'Sets in list_of_sets:'
      for s in list_of_sets:
          print s
      print
      
      #Get intersection of all the sets
      print 'Numbers less than or equal to %d that are coprime to it:' % n
      print reduce(set.intersection, list_of_sets)
      

      输出

      Sets in list_of_sets:
      set([1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29])
      set([1, 2, 4, 5, 7, 8, 10, 11, 13, 14, 16, 17, 19, 20, 22, 23, 25, 26, 28, 29])
      set([1, 2, 3, 5, 6, 7, 9, 10, 11, 13, 14, 15, 17, 18, 19, 21, 22, 23, 25, 26, 27, 29, 30])
      set([1, 2, 3, 4, 6, 7, 8, 9, 11, 12, 13, 14, 16, 17, 18, 19, 21, 22, 23, 24, 26, 27, 28, 29])
      
      Numbers less than or equal to 30 that are coprime to it:
      set([1, 7, 11, 13, 17, 19, 23, 29])
      

      实际上,我们甚至不需要reduce(),我们可以这样做

      set.intersection(*list_of_sets)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-10-16
        相关资源
        最近更新 更多