【问题标题】:How to pass list of sets as separate arguments into function? [duplicate]如何将集合列表作为单独的参数传递给函数? [复制]
【发布时间】:2014-02-15 02:20:28
【问题描述】:

我已经创建了一个我想传递给 set.intersection() 的集合列表

例如:

List_of_Sets = [{1,2,3},{3,4,5},{5,6,7}]
set.intersection(List_of_Sets)

结果:

TypeError: descriptor 'intersection' requires a 'set' object but received a 'list'

期望的输出:

{3,5}

如何将列表中的每个集合作为单独的参数传递给 set.intersection()?

【问题讨论】:

  • 请说明您要执行的操作。 {1,2,3} intersect {3,4,5} intersect {5,6,7} 不是 {3,5} 而是 {}...
  • @mgilson 我不确定这些重复,答案是相同的,但问题不是。
  • @SteinarLima,但是只要它适用于新功能,我们是否允许每个解包问题?
  • @mhlester 我不知道。 Meta 可能有一些关于它的讨论。
  • @SteinarLima -- 我之前看到的问题的相似度比这要少,但与往常一样,我的 1 次近距离投票还不够。我们还需要 4 个 ;-)。由社区决定。

标签: python list function set


【解决方案1】:

使用解包操作符:set.intersection(*List_of_Sets)


正如另一个答案中所指出的,您在列表中没有交集。是否要计算相邻元素交集的并集?

>>> set.union(*[x & y for x, y in zip(List_of_Sets, List_of_Sets[1:])])
set([3, 5])

【讨论】:

  • 或者,如果你真的喜欢mapset.union(*map(operator.__and__,*zip(List_of_Sets, List_of_Sets[1:])))
【解决方案2】:
>>> List_of_Sets = [{1,2,3},{3,4,5},{5,6,7}]
>>> set.intersection(*List_of_Sets)  # * unpacks list into arguments
set([])

该集合中没有交集,因此它返回一个空集合。一个工作示例:

>>> List_of_Sets2 = [{1,2,3},{3,4,5},{5,6,3}]
>>> set.intersection(*List_of_Sets2)  # * unpacks list into arguments
set([3])

Docs on unpacking with *

【讨论】:

  • “没有交叉点”这一点很好。
猜你喜欢
  • 1970-01-01
  • 2016-07-22
  • 1970-01-01
  • 2011-06-10
  • 2012-12-24
  • 1970-01-01
  • 2018-03-13
  • 2015-06-23
  • 1970-01-01
相关资源
最近更新 更多