【问题标题】:How to convert a list of lists into a singular set如何将列表列表转换为单数集合
【发布时间】:2019-01-30 16:17:54
【问题描述】:

当试图在setOfsets 中查找集合的交集时,会出现下面提到的错误。

示例 setA = [['1','2'], ['2,3'], '['2','4']]

我知道它不能有“Lists”数据类型的交集,我尝试将它转换为一个集合,但它不起作用

def multiple_set_intersection(*sets):
    """Return multiple set intersection."""
    try:
        return set.intersection(*sets)
    except TypeError: # this is Python < 2.6 or no arguments
        pass

    try: a_set= sets[0]
    except IndexError: # no arguments
        return set() # return empty set

    return reduce(a_set.intersection, sets[1:])

multiple_set_intersection(*setOfSets)

预期结果:setOfSets 内部存在的所有集合的交集,即 intersection = 2

实际结果:

return reduce(a_set.intersection, sets[1:])
AttributeError: 'list' object has no attribute 'intersection'

【问题讨论】:

  • 请分享列表,这样更容易回答
  • setA 并且其中的元素是列表而不是集合
  • 那么消耗的输出是多少?
  • 请分享setOfSets的完整列表
  • 列表列表是一个数组

标签: python python-3.x set


【解决方案1】:

将您的列表转换为先设置。因为set.intersectionset 的方法,而不是list 的方法。

  • 假设您的setOfSets 包含列表列表。请参阅代码中的示例。您可以做的是在调用set.interseciton 时映射要设置的每个列表。
def multiple_set_intersection(*sets):
    """Return multiple set intersection."""
    try:
        return set.intersection(*map(set,sets))
    except TypeError: # this is Python < 2.6 or no arguments
        pass

    try: a_set= map(set,sets[0])
    except IndexError: # no arguments
        return set() # return empty set

    return set.intersection(*map(set,l))

setOfSets = [['1','2'], ['2','3'], ['2','4']]
print(multiple_set_intersection(*setOfSets))


PS:如果您的输入与上述代码中指定的一样,那么这将起作用。

【讨论】:

  • 我只是把整个函数去掉,写了一个简单的for循环
  • for z in range(0, num): intersectionOfall= set(setOfSets[z]).intersection(*setOfSets)
  • @SakshatShinde 检查这个更新的解决方案,它适用于您的给定输入。我希望这是您正在尝试做的事情。
  • 是的,很简单
  • 谢谢!希望它会帮助其他人,以防有人试图以不同的方式实现它
猜你喜欢
  • 2010-10-09
  • 1970-01-01
  • 2011-01-29
  • 1970-01-01
  • 1970-01-01
  • 2022-11-12
  • 2013-12-16
  • 1970-01-01
  • 2017-02-06
相关资源
最近更新 更多